我认为您的定义非常接近(如下所示)。但是,如果使用非JavaBeans方法,您可能会失去大多数工具提供的支持,这些工具假定JavaBeans协议正在生效。请注意,以下代码都是我临时想到的...
public class Property<T> {
public final String name;
T value;
private final PropertyChangeSupport support;
public static <T> Property<T> newInstance(String name, T value,
PropertyChangeSupport support) {
return new Property<T>(name, value, support);
}
public static <T> Property<T> newInstance(String name, T value) {
return newInstance(name, value, null);
}
public Property(String name, T value, PropertyChangeSupport support) {
this.name = name;
this.value = value;
this.support = support;
}
public T getValue() { return value; }
public void setValue(T value) {
T old = this.value;
this.value = value;
if(support != null)
support.firePropertyChange(name, old, this.value);
}
public String toString() { return value.toString(); }
}
然后继续使用它:
public class Customer {
private final PropertyChangeSupport support = new PropertyChangeSupport();
public final Property<String> name = Property.newInstance("name", "", support);
public final Property<Integer> age = Property.newInstance("age", 0, support);
... declare add/remove listenener ...
}
Customer c = new Customer();
c.name.setValue("Hyrum");
c.age.setValue(49);
System.out.println("%s : %s", c.name, c.age);
因此,现在声明一个属性只需要一行代码,并且包括属性更改支持。我调用了setValue()和getValue()方法,这样它看起来仍然像是一个bean,对于类似Rhino的代码等,但为了简洁起见,您可以仅添加get()和set()。其余部分留给读者作为练习:
- 正确处理序列化
- 处理null值检查
- 如果您关心自动装箱开销,则可以为原子类型添加专业知识。
- ??我相信还有更多要注意的地方
还要注意,您可以子类化(通常作为匿名类),并覆盖setValue()以提供额外的参数检查。
我认为您真的无法摆脱"字符串引用",因为这基本上就是反射的全部内容。
不幸的是,在现今这个时代,这仍然有点像汇编语言编程...如果您有选择,Groovy、C#等可能仍然是更好的选择。