简而言之,是的,可以在运行时修改字节码,但它可能非常混乱,并且(很可能)不是您想要的方法.但是,如果您决定采用这种方法,我建议使用字节代码操作库,例如ASM.
更好的方法是使用Map< String,String>对于“动态”getter和setter,以及Map< String,Callable< Object>>对于任何不是吸气剂或二传手的东西.然而,最好的方法可能是重新考虑为什么你需要动态类.
public class Student {
private Map properties = new HashMap();
private Map> callables = new HashMap>();
....
....
public String getProperty(String key) {
return properties.get(key);
}
public void setProperty(String key, String value) {
properties.put(key, value);
}
public Object call(String key) {
Callable callable = callables.get(key);
if (callable != null) {
return callable.call();
}
return null;
}
public void define(String key, Callable callable) {
callables.put(key, callable);
}
}
作为注释,您可以使用Callable并在其中返回null来使用此概念定义void方法.