有没有什么办法可以在运行时将新方法和属性注入到类中.
http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.html声明我们可以通过使用Groovy来做到这一点.
只使用Java可以吗?
我希望能够在运行时动态地为现有类(对象)设置属性。
例如,具有 接口MyProperty.java以及实现该接口的其他特定属性。然后拥有一个可以动态接收某个实例MyProperty并自动为其提供getter 的对象。
MyPropery.java [表示某些对象属性的接口]
public interface MyProperty {
String getValue();
}
Run Code Online (Sandbox Code Playgroud)
MyPropertyAge.java [一些特定的对象属性]
public class MyPropertyAge implements MyProperty {
private final String age;
public MyPropertyAge(String age) {
this.age = age;
}
@Override
public String getValue() {
return age;
}
}
Run Code Online (Sandbox Code Playgroud)
MyObject.java [应该动态具有 MyProperty getter 的对象]
public class MyObject {
public MyObject(Set<MyProperty> properties) {
// receive list of properties,
// and have getters for them
}
// For example, if I passed in a …Run Code Online (Sandbox Code Playgroud)