简体   繁体   English

Java抽象类型类编译时间检查

[英]Java abstract type Class compile time check

Is it possible somehow to check at COMPILE time do classType points to an abstract type? 是否有可能在COMPILE时检查classType是否指向抽象类型? 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. 您可以编写自己的@MustBeAbstract注释,然后编写一个注释处理器,以强制带有该注释的任何类都是抽象的。

See this question on annnotation processing: What is annotation processing in Java? 请参见有关注释处理的问题: 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. 但是,如果您事先知道传递给方法foo的类的列表,则可以实现手动解决方案。 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...   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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