Reputation: 21
I am using the string to get a Class name and the using the Class.forName() to get a Class.
Now I want to know if this class is an instance of another class (in this case java.lang.AutoCloseable).
My code is
Class c = Class.forName("java.io.FileInputStream");
if(c instanceof java.lang.AutoCloseable){
//detected that FileInputStream implements AutoCloseable
}
But it doesn't seem to work. I have also tried c.newInstance() and c.getClass().newInstance() but neither work and throw exceptions. Please help!
Upvotes: 2
Views: 1672
Reputation: 1879
Class c = Class.forName("java.io.FileInputStream");
if(c instanceof java.lang.AutoCloseable){
//detected that FileInputStream implements AutoCloseable
}
TO
Class c = Class.forName("java.io.FileInputStream");
if(java.lang.AutoCloseable.class.isAssignableFrom(c)){
//detected that FileInputStream implements AutoCloseable
}
Upvotes: 1
Reputation: 135992
try something like this
boolean isComparable = Comparable.class.isAssignableFrom(cls));
Upvotes: 0