Spring boot – Get generic class type and name in abstract class without constructor

Advertisements

My Class:

public class MyClass extends AbstracyEntity {
   
   ...

}

My Service:

@Service
@RequiredArgsConstructor
public class MyService extends MyAbstractService<MyClass> {
   
   ...

}

My Abstract Class:

public abstract class MyAbstractService<E extends AbstracyEntity> {
   
   public void myAbstractMethod() {
      Class<?> c = E.getClass();
      System.out.println(c.getSimpleName());
   }

}

Finally expected output from Abstract Service -> myAbstractMethod() :

MyClass

From whatever entity my abstracted service is abstracted from, I need the related entity’s type and class name. Because I aim to create dynamic queries with common conditions with entity name. Example:

String sql = "Select t From " + E.getClass.getSimpleName() + " t where ...";

I solved the problem by defining a constructor in an abstract class, but I don’t think it’s the best solution.What is the best solution?

>Solution :

You may infer generic type parameter via something like:

ResolvableType type = 
 ResolvableType.forClass(getClass()).as(MyAbstractService.class);
Class<?>[] typeArguments = type.resolveGenerics(Object.class);
return (Class<E>) typeArguments[0];

However nothing prevents you from writing that in more clear way:

public abstract class MyAbstractService<E extends AbstracyEntity> {

   private Class<E> type;

   pubic MyAbstractService(Class<E> type) {
       this.type = type;
   }

}

public class MyService extends MyAbstractService<MyClass> {

    pubic MyService() {
        super(MyClass.class);
    }
}

Leave a ReplyCancel reply