小编Ste*_*ves的帖子

使用反射设置对象属性

我按名称获取类,我需要使用相应的数据更新它们,我的问题是如何使用java我想要添加方法一些虚拟数据.我不知道类类型我只是获取类名并使用反射来获取他的数据

我使用此代码来获取类实例和

Class<?> classHandle = Class.forName(className);

Object myObject = classHandle.newInstance();

// iterate through all the methods declared by the class
for (Method method : classHandle.getMethods()) {
    // find all the set methods
    if (method.getName().matches("set[A-Z].*")
Run Code Online (Sandbox Code Playgroud)

并且知道我找到了我想用数据更新它的set方法的列表我该怎么做.

假设在类名中我得到了人,而且类有setSalary和setFirstName等我怎样才能用反射设置它们?

public class Person {

    public void setSalery(double salery) {
        this.salery = salery;
    }

    public void setFirstName(String FirstName) {
        this.FirstName = FirstName;
    }   
}
Run Code Online (Sandbox Code Playgroud)

java reflection accessor

25
推荐指数
2
解决办法
7万
查看次数

标签 统计

accessor ×1

java ×1

reflection ×1