如何为java对象动态添加属性? [英] How to add attributes Dynamically for java object?

查看:1012
本文介绍了如何为java对象动态添加属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有学生班。

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

    public Student(){
    }
}

是否有可能向Student对象添加动态属性?
没有延长学生班级。

is there any possibility to add dynamic attributes to Student Object? without extending the student class.

推荐答案

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

In short, yes it is possible to modify bytecode at runtime, but it can be extremely messy and it (most likely) isn't the approach you want. However, if you decide to take this approach, I recommend a byte code manipulation library such as ASM.

更好的方法是使用映射< String,String> 用于动态getter和setter,以及 Map< String,Callable< Object>> 用于任何非不是一个吸气鬼或二传手。然而,最好的方法可能是重新考虑你为什么需要动态课程。

The better approach would be to use a Map<String, String> for "dynamic" getters and setters, and a Map<String, Callable<Object>> for anything that isn't a getter or setter. Yet, the best approach may be to reconsider why you need dynamic classes altogether.

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);
    }
}

作为备注,你可以使用Callable定义void方法,使用Callable并在其中返回null。

As a note, you can define void methods with this concept by using Callable and returning null in it.

这篇关于如何为java对象动态添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆