user3534334
user3534334

Reputation: 21

How to check if a Class.forName() implements a particular interface?

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

Answers (2)

tianwei
tianwei

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

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try something like this

boolean isComparable = Comparable.class.isAssignableFrom(cls));

Upvotes: 0

Related Questions