英文:
pass parameter to jpa converter
问题
我正试图编写一个通用的 Converter
,以在代码中的多个类似情况下重复使用。我有一组子类,我想使用一个 Converter
来处理它们,因此我想要传递一些东西(类类型/某些参数/等等)到 Converter
,以便能够定义:
public class GenericConverter implements AttributeConverter<MyGenericClass, Integer> {
.
.
.
public MyGenericClass convertToEntityAttribute(Integer arg0) {
// 根据属性/初始化方法/等等在这里返回特定的子类
}
并且在实体中:
@Convert(converter = GenericConverter.class /*在这里传递一些东西*/)
protected SubClass1 var1;
@Convert(converter = GenericConverter.class /*在这里传递一些东西*/)
protected SubClass2 var2;
@Convert(converter = GenericConverter.class, /*在这里传递一些东西*/)
protected SubClass3 var3;
这是否可行?
英文:
I am trying to write a generic Converter
to be used in multiple similar cases in my code. I have a set of subclasses that I want to handle using only one Converter
, so I want to pass something (class type / some parameter / etc) to the Converter
to be able to define
public class GenericConverter implements AttributeConverter<MyGenericClass , Integer> {
.
.
.
public MyGenericClass convertToEntityAttribute(Integer arg0) {
// return a certain sub class here according to an attribute / an initialization method / etc
}
and in the entities:
@Convert( converter = GenericConverter.class \*pass something here\* )
protected SubClass1 var1;
@Convert( converter = GenericConverter.class \*pass something here\* )
protected SubClass2 var2;
@Convert( converter = GenericConverter.class, \*pass something here\* )
protected SubClass3 var3;
Is this doable by any means?
答案1
得分: 1
我想将一些东西(类类型 / 某些参数 / 等等)传递给转换器以便进行定义。
我唯一能想到的方法是将 GenericConverter
声明为抽象类,定义一个带有你想要修改的参数的构造函数:
public abstract GenericConverter {
protected GenericConverter(Class<?> type, String someParameter, Object etc){
....
}
}
然后创建子类并传递这些参数:
public class SubClass1Converter extends GenericConverter {
public SubClass1Converter(){
super(SubClass1.class, "someValue", ....);
}
}
然后你可以在 @Convert
中使用这些子类:
@Convert(converter = SubClass1Converter.class)
我没有看到其他好的选择,因为 AttributeConverter
接口不会将转换的 Field
(AnnotatedElement
)传递给你。因此,你无法创建自己的注解并查找这个注解。
英文:
> I want to pass something (class type / some parameter / etc) to the Converter to be able to define
The only way I see is to make the GenericConverter
abstract, define a constructor with the parameters you would like to modify
public abstract GenericConverter {
protected GenericConverter(Class<?> type, String someParameter, Object etc){
....
}
}
create subclasses and pass that arguments.
public class SubClass1Converter extends GenericConverter {
public SubClass1Converter(){
super(SubClass1.class, "someValue", ....);
}
}
Then you can use the subclasses in the @Convert
.
@Convert(converter = SubClass1Converter.class)
I don't see other good options since the AttributeConverter
interface does not pass you the Field
(AnnotatedElement
) that is converted. Thus you can't create an own annotation and lookup this one.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论