0

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?

lietus
  • 199
  • 2
  • 11
  • could you please tell us the reason you want to check the type at compile time ? What I think was finding the type at the run time is the thing that most programmers worrying about. (since there may be different implementation which has so many specific methods(rather than the overridden methods)) – Eshan Sudharaka Apr 18 '12 at 08:04
  • Method needs type information to find objects of this type in private members. That abstract subclass type should define a group of possible implementations, not implementation itself, so compile time check if argument is of abstract type would help prevent mistakes in usage. – lietus Apr 20 '12 at 06:24

2 Answers2

3

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?

Community
  • 1
  • 1
daveb
  • 74,111
  • 6
  • 45
  • 51
0

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. i.e.

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...   
}
JeanValjean
  • 17,172
  • 23
  • 113
  • 157