Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

My Class:

public class MyClass extends AbstracyEntity {
   
   ...

}

My Service:

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

}

My Abstract Class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    }
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading