Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a Java class is abstract by reflection

People also ask

How do you check if a class is an abstract class?

The Modifier#isAbstract Method In the example above, we first obtain the instance of the class we want to test. Once we have the class reference, we can call the Modifier#isAbstract method. As we'd expect, it returns true if the class is abstract, and otherwise, it returns false.

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

How do you find the instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.


It'll have abstract as one of its modifiers when you call getModifiers() on the class object.

This link should help.

 Modifier.isAbstract( someClass.getModifiers() );

Also:

http://java.sun.com/javase/6/docs/api/java/lang/reflect/Modifier.html

http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getModifiers()


Class myClass = myJar.load("classname");
bool test = Modifier.isAbstract(myClass.getModifiers());

public static boolean isInstantiable(Class<?> clz) {
    if(clz.isPrimitive() || Modifier.isAbstract( clz.getModifiers()) ||clz.isInterface()  || clz.isArray() || String.class.getName().equals(clz.getName()) || Integer.class.getName().equals(clz.getName())){
        return false;
    }
    return true;
}