通过反射将新方法添加到类中 [英] Adding new method to a class through reflection

查看:69
本文介绍了通过反射将新方法添加到类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过Java中的反射将方法添加到类中?

Is it possible to add a method to a class through reflection in java??

public class BaseDomain {

    public BaseDomain(){
        Field[] fields = this.getClass().getDeclaredFields();
        for(int i=0; i<fields.length; i++){
            String field = fields[i].toString();

            String setterMethod = "public void set" + field.toLowerCase();

            //Now I want to add this method to this class.

        }
    }
}

推荐答案

不,不是通过反射.

Reflection询问有关类及其成员的信息,您可以更改字段,但不能创建新的字段.您无法添加新方法.

Reflection asks about classes and their members, you can change fields but you cannot create new ones. You cannot add new methods.

您可以使用aa 字节码操作库添加方法上课但是你为什么要这么做?

You can use a a bytecode manipulation library to add methods to classes; but why would you want to?

无论如何都不能通过反射调用这些方法,因为它们在编译时显然不存在.

You can't call the methods anyway except via reflection as they would obviously not exist at compile time.

也许看看项目龙目岛-这是一个注释预处理器,可以在编译时将方法添加到类中.只要正确注释了类,它将自动添加getter和setter.

Maybe take a look at project Lombok - this is a annotation preprocessor that can add methods to classes at compile time. It will add getters and setters automagically as long as your classes are correctly annotated.

这篇关于通过反射将新方法添加到类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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