英文:
Get generic class type and name in abstract class without constructor
问题
我的类:
public class MyClass extends AbstracyEntity {
...
}
我的服务:
@Service
@RequiredArgsConstructor
public class MyService extends MyAbstractService<MyClass> {
...
}
我的抽象类:
public abstract class MyAbstractService<E extends AbstracyEntity> {
public void myAbstractMethod() {
Class<?> c = E.getClass();
System.out.println(c.getSimpleName());
}
}
最终期望的抽象服务输出 -> myAbstractMethod():
MyClass
从我的抽象服务抽象出的任何实体,我需要相关实体的类型和类名。因为我想用实体名创建具有共同条件的动态查询。例如:
String sql = "Select t From " + E.getClass.getSimpleName() + " t where ...";
我通过在抽象类中定义一个构造函数来解决了这个问题,但我认为这不是最好的解决办法。什么是最好的解决办法?
英文:
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?
答案1
得分: 1
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 a clearer way:
public abstract class MyAbstractService<E extends AbstractEntity> {
private Class<E> type;
public MyAbstractService(Class<E> type) {
this.type = type;
}
}
public class MyService extends MyAbstractService<MyClass> {
public MyService() {
super(MyClass.class);
}
}
英文:
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论