你總是可以使用Java Reflection。
獲取的屬性列表
for (Method method : Node.class.getMethods()) {
String name = method.getName();
if (name.endsWith("Property")) {
Type returnType = method.getReturnType();
String propName = name.replace("Property", "");
System.out.println(propName + " : " + returnType);
}
}
下面是綁定和例如反射方法:
public class ReflectiveBind extends Application {
/**
* Reflection call for code like
* slider1.valueProperty().bindBidirectional(slider2.valueProperty());
*
* @param bindee Node which you want to be changed by binding
* @param propertyName name of the property, e.g. width
* @param bindTarget Node which you want to be updated by binding
*/
private static void bind(Object bindee, String propertyName, Object bindTarget) throws Exception {
// here we get slider1.valueProperty()
Method methodForBindee = bindee.getClass().getMethod(propertyName + "Property", (Class[]) null);
Object bindableObj = methodForBindee.invoke(bindee);
// here we get slider2.valueProperty()
Method methodForBindTarget = bindTarget.getClass().getMethod(propertyName + "Property", (Class[]) null);
Object bindTargetObj = methodForBindTarget.invoke(bindTarget);
// here we call bindBidirectional: slider1.valueProperty().bindBidirectional(slider2.valueProperty())
Method bindMethod = bindableObj.getClass().getMethod("bindBidirectional", Property.class);
bindMethod.invoke(bindableObj, bindTargetObj);
}
@Override
public void start(Stage stage) {
Slider slider1 = new Slider();
Slider slider2 = new Slider();
VBox root = new VBox(20);
root.getChildren().addAll(slider1, slider2);
stage.setScene(new Scene(root, 200, 100));
stage.show();
try {
//same call as slider1.valueProperty().bindBidirectional(slider2.valueProperty());
bind(slider1, "value", slider2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) { launch(); }
}
綁定的方法看起來不錯。我嘗試過,但遇到了ClastCastException,也是它的雙向。我還沒有完全剖析整個邏輯,所以我不確定我可以做些什麼來適應我的需要。 – Fozz 2012-08-06 20:40:22
我已經改變了調用雙向綁定的方法,添加了javadoc並提供了一個演示應用的應用程序。 – 2012-08-07 10:06:26