简体   繁体   中英

Java abstract type Class compile time check

Is it possible somehow to check at COMPILE time do classType points to an abstract type? Runtime check can be done:

void foo(Class<? extends SubType> classType) {
    Modifier.isAbstract(classType.getModifiers()); 
}

foo(AbstractType.class);    // this should pass
foo(NotAbstractType.class); // this should fail

If same could be done at COMPILE time?

You could write your own @MustBeAbstract annnotation and then an annnotation processor that enforces that any class with that annnotation is abstract.

See this question on annnotation processing: What is annotation processing in Java?

To my knowledge, there is no automatic solution.

However, if you know in advance the list of classes that are passed to method foo, you can implement a manual solution. ie

private ArrayList<Class> abstractTypes = new ArrayList<>();

void foo(Class<? extends SubType> classType) {
    boolean isAbstract = false;
    for(Class c: abstractTypes)
       if((classType.getName()).equals(c.getName()){
          isAbstract = true;
          break;
       }

    //Do something else...   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM