[英]Can you add a decorator to parent methods and variables from a child class?
是否可以将 @ 装饰器添加到父类的字段或方法而不隐藏它(不使用超级)?
下面的代码产生:
colA = null , colA = Hello World, ttl = 360
注意 toString 的父级为 null
abstract class TableA {
protected String colA;
public String toString() {
return "colA = " + this.colA;
}
}
class TableAImpl extends TableA {
//@Computed("ttl(value)")
int myTtl;
//*** NOTICE THIS ***
//@PartitionKey
protected String colA;
public TableAImpl(int ttl, String colA) {
this.myTtl = ttl;
this.colA = colA;
}
//*** NOTICE THIS ***
public String toString() {
return super.toString() + ", colA = " + this.colA + ", ttl = " + this.myTtl;
}
}
public class HelloWorld{
public static void main(String []args){
TableAImpl a = new TableAImpl(360, "Hello World");
System.out.println(a.toString());
}
}
语境:
我需要支持多种数据库类型,所以我有一个通用的实体类,它被数据库特定的实现类重载。 这些特定于 DB 的类重载/添加特定逻辑以与该 DB 接口,这对调用者来说应该是不可见的。
对于使用的 DB 之一,java 驱动程序的逻辑主要是通过将 @Decorators 添加到实体类的方法和属性来完成的,实体类的方法和属性用于生成帮助程序代码。
当我尝试使用下面的代码向它们添加装饰器时,子类的变量隐藏了父类的变量
您从未设置过父级的colA
属性。
public TableAImpl(int ttl, String colA) {
this.myTtl = ttl;
this.colA = colA;
super.colA = colA;
}
为了保护父母的colA
您应该使用private
和getter
将其设置为私有,如下所示:
abstract class TableA {
private String colA;
public TableA() {}
public TableA(String colA) {
this.colA = colA;
}
public String toString() {
return "colA = " + this.colA;
}
protected String getColA() {
return colA;
}
}
class TableAImpl extends TableA {
//@Computed("ttl(value)")
int myTtl;
public TableAImpl(int ttl, String colA) {
super(colA);
this.myTtl = ttl;
}
public String toString() {
return super.toString() + ", colA = " + this.getColA() + ", ttl = " + this.myTtl;
}
//*** NOTICE THIS ***
//@PartitionKey
@Override
public String getColA() {
return super.getColA();
}
}
public class Main{
public static void main(String []args){
TableAImpl a = new TableAImpl(360, "Hello World");
System.out.println(a.toString());
// colA = Hello World, colA = Hello World, ttl = 360
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.