Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you're pretty close with the declaration you have there (see below for a sketch). However, by using a non-beans approach, you'll probably lose support provided by most tools that assume the JavaBeans protocol is in effect. Please be kind. The code below is off the top of my head...</p> <pre><code>public class Property&lt;T&gt; { public final String name; T value; private final PropertyChangeSupport support; public static &lt;T&gt; Property&lt;T&gt; newInstance(String name, T value, PropertyChangeSupport support) { return new Property&lt;T&gt;(name, value, support); } public static &lt;T&gt; Property&lt;T&gt; 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(); } } </code></pre> <p>and then go ahead and use it:</p> <pre><code>public class Customer { private final PropertyChangeSupport support = new PropertyChangeSupport(); public final Property&lt;String&gt; name = Property.newInstance("name", "", support); public final Property&lt;Integer&gt; 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); </code></pre> <p>So, now declaring a property is a single line of code and property change support is included. I called the methods setValue() and getValue() so it would still look like a bean to code like Rhino and stuff, but for succinctness, you could add just get() and set(). The rest is left as an exercise for the reader:</p> <ul> <li>Properly handle serialization</li> <li>Handle null value checking</li> <li>Maybe add a specializations for atomic types if you care about autoboxing overhead.</li> <li>?? I'm sure there are more gotchas</li> </ul> <p>Also note that you can subclass (usually as an anonymous class) and override setValue() to provide additional parameter checking. </p> <p>I don't think you can really get away from "String references" since that's pretty much what reflection's all about.</p> <p>Sadly though, in this day and age, this is still kind of like programming in assembly... Groovy, C#, etc, etc may still be a better choice, if you have a choice.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload