将Getters / Setter添加到一个基类 [英] Adding Getters/Setters to one Base class
问题描述
public class BaseDomain< T>< p> {
//通用方法在此处
}
public class Domain1扩展BaseDomain< Domain1> {
private int id;
私人字符串名称;
//只有属性应该存在这里
}
public class Domain2扩展BaseDomain< Domain2> {
private int id;
私人字符串名称;
//只有属性应该在这里存在
}
在上面的场景中,我可以轻松地定义基类中的所有泛型方法,并可以使用泛型将其用于所有域类。但我的问题在于我想设计一个机制,开发人员只需要在域类中定义属性(无需getters / setters),但BaseDomain应该为每个域动态地提供
getters / setters。
任何建议都非常感谢!
使用反射你可以做到这一点。
public class BaseDomain< T> {
public String getName(){
返回this.getClass()。getField(name)。get(this);
}
public void setName(String value){
this.getClass()。getField(name)。set(this,value);
}
}
请注意 this.getClass()
将引用该对象的运行时类,例如 Domain1
。因此,您可以访问这些字段,获取/设置值等。
如果您将属性声明为,则可能需要设置访问权限。私人
或保护
。它们是 public
,它应该工作。
正如OP提到的,使用 getDeclaredFields()
不会强制你声明公有字段,不幸的是你必须迭代通过(或使用 Map
)以特定名称访问字段
。
如果该字段不存在于您的对象实例中,您将得到一个异常。
I got one thought, but not able to figure it out how to implement this.
public class BaseDomain<T>{
//Generic methods goes here
}
public class Domain1 extends BaseDomain<Domain1>{
private int id;
private String name;
//only properties should be present here
}
public class Domain2 extends BaseDomain<Domain2>{
private int id;
private String name;
//only properties should be present here
}
In above scenario, easily I can define all generic methods in base class and can use in all my domain classes by using generics. But My problem here is I want to design a mechanisim by which developer's have to define only properties in a domain class(without getters/setters) however somehow BaseDomain should provide getters/setters dynamically to each domain.
Any suggestion greatly appreciated!
With Reflection you can do that.
public class BaseDomain<T>{
public String getName() {
return this.getClass().getField("name").get(this);
}
public void setName(String value) {
this.getClass().getField("name").set(this, value);
}
}
Note that this.getClass()
will refer to the runtime class of that object, that is Domain1
for example. So, you can access the fields there, get/set values, etc.
You may need to set access privileges if you declare the properties to private
or protected
. It they're public
, it should work.
As OP mentioned, using getDeclaredFields()
will not force you to declare public fields, unfortunately you have to iterate through (or use a Map
) to access the Field
with a specific name.
If the field is not present in your object instance, you'll get an exception.
这篇关于将Getters / Setter添加到一个基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!