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

前端 未结 3 669
自闭症患者
自闭症患者 2020-12-02 14:54

I am interating through classes in a Jar file and wish to find those which are not abstract. I can solve this by instantiating the classes and trapping InstantiationExceptio

相关标签:
3条回答
  • 2020-12-02 15:41

    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()

    0 讨论(0)
  • 2020-12-02 15:46
    Class myClass = myJar.load("classname");
    bool test = Modifier.isAbstract(myClass.getModifiers());
    
    0 讨论(0)
  • 2020-12-02 15:47
    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;
    }
    
    0 讨论(0)
提交回复
热议问题