如何为java对象动态添加属性?

use*_*029 6 java

有学生班.

Class Student{
    String _name;
    ....
    ....

    public Student(){
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能向Student对象添加动态属性? 没有扩展学生班.

FTh*_*son 16

简而言之,是的,可以在运行时修改字节码,但它可能非常混乱,并且(很可能)不是您想要的方法.但是,如果您决定采用这种方法,我建议使用字节码操作库,例如ASM.

更好的方法是使用Map<String, String>"动态"getter和setter,以及Map<String, Callable<Object>>任何不是getter或setter的东西.然而,最好的方法可能是重新考虑为什么你需要动态类.

public class Student {

    private Map<String, String> properties = new HashMap<String, String>();
    private Map<String, Callable<Object>> callables = new HashMap<String, Callable<Object>>();
    ....
    ....
    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<Object> callable = callables.get(key);
        if (callable != null) {
            return callable.call();
        }
        return null;
    }

    public void define(String key, Callable<Object> callable) {
        callables.put(key, callable);
    }
}
Run Code Online (Sandbox Code Playgroud)

作为注释,您可以通过使用Callable并在其中返回null来使用此概念定义void方法.


Jim*_*son 7

你可以进入字节码操作,但这种方式是疯狂的(特别是对于必须维护代码的程序员).

将属性存储在一个Map<String,String>替代.