Using the general type of subclass in it is an abstract superclass?

In my code a there is the following abstract superclass

public abstract class AbstractClass<Type extends A> {...} 

and some child classes like

 public class ChildClassA extends AbstractClass<GenericTypeA> {...} public class ChildClassB extends AbstractClass<GenericTypeB> {...} 

I am looking for an elegant way in which I can use the generic type of child classes (GenericTypeA, GenericTypeB, ...) inside an abstract class in a generic way.

To solve this problem, I have currently defined a method

 protected abstract Class<Type> getGenericTypeClass(); 

in my abstract class and implemented a method

 @Override protected Class<GenericType> getGenericTypeClass() { return GenericType.class; } 

in each child class.

Is it possible to get the generic type of child classes in my abstract class without implementing this helper method?

BR

Marcus

+6
java generics class abstract-class
source share
2 answers

I think it's possible. I saw that it was used in DAO templates along with generics. For example, consider the classes:

 public class A {} public class B extends A {} 

And your general class:

  import java.lang.reflect.ParameterizedType; public abstract class Test<T extends A> { private Class<T> theType; public Test() { theType = (Class<T>) ( (ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; } // this method will always return the type that extends class "A" public Class<T> getTheType() { return theType; } public void printType() { Class<T> clazz = getTheType(); System.out.println(clazz); } } 

You may have a class Test1 that extends Test with class B (it extends A)

  public class Test1 extends Test<B> { public static void main(String[] args) { Test1 t = new Test1(); Class<B> clazz = t.getTheType(); System.out.println(clazz); // will print 'class B' System.out.println(printType()); // will print 'class B' } } 
+10
source share

I'm not sure I fully understand your question. <Type> is a generic subclass type, even if it is expressed in an abstract class. For example, if your abstract superclass defines a method:

 public void augment(Type entity) { ... } 

and you create an instance of ChildClassA , you can only call augment with an instance of GenericTypeA .

Now, if you need a class literal, you need to provide a method, as you indicated. But if you just need a general parameter, you don’t need to do anything special.

0
source share

All Articles