[英]Can you add a decorator to parent methods and variables from a child class?
Is it possible to add a @ decorator to a parent class's field or method without hiding it (without using super)?是否可以将 @ 装饰器添加到父类的字段或方法而不隐藏它(不使用超级)?
Code below produces:下面的代码产生:
colA = null , colA = Hello World, ttl = 360 colA = null , colA = Hello World, ttl = 360
notice the toString has null for the parent注意 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());
}
}
Context:语境:
I need to support multiple database types so I have a generic Entity class which are overloaded by DB specific Implementation classes.我需要支持多种数据库类型,所以我有一个通用的实体类,它被数据库特定的实现类重载。 These DB specific classes overload/add the specific logic to interface with that DB, which should be invisible to the caller.这些特定于 DB 的类重载/添加特定逻辑以与该 DB 接口,这对调用者来说应该是不可见的。
For one of the DBs used, the java driver's logic is primarily done by adding @Decorators to the Entity Class's methods and attributes which it uses to generate helper code.对于使用的 DB 之一,java 驱动程序的逻辑主要是通过将 @Decorators 添加到实体类的方法和属性来完成的,实体类的方法和属性用于生成帮助程序代码。
When I try the below code to add decorators to them, the child class's variables hide the parent's当我尝试使用下面的代码向它们添加装饰器时,子类的变量隐藏了父类的变量
You've never set parent's colA
attribute.您从未设置过父级的colA
属性。
public TableAImpl(int ttl, String colA) {
this.myTtl = ttl;
this.colA = colA;
super.colA = colA;
}
To protect parent's colA
you should set it private with private
and a getter
like so :为了保护父母的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.