Java 使用反射设置对象属性

Java 使用反射设置对象属性,java,reflection,accessor,Java,Reflection,Accessor,我按名称获取类,需要用相应的数据更新它们,我的问题是如何用java实现 我想给这个方法添加一些虚拟数据。 我不知道类的类型,我只是获取类名并使用反射来获取他的数据 我使用这段代码来获取类实例和 Class<?> classHandle = Class.forName(className); Object myObject = classHandle.newInstance(); // iterate through all the methods declared by the

我按名称获取类,需要用相应的数据更新它们,我的问题是如何用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].*")
要了解参数,可以发出
method.getPagetParameterTypes()

根据结果构造参数和供应。

您也可以使用反射直接将值设置为属性,而不是尝试调用setter。例如:

公共静态布尔集(对象对象、字符串字段名、对象字段值){
Class clazz=object.getClass();
while(clazz!=null){
试一试{
字段字段=clazz.getDeclaredField(字段名);
字段。setAccessible(true);
设置(对象、字段值);
返回true;
}捕获(无此字段例外){
clazz=clazz.getSuperclass();
}捕获(例外e){
抛出新的非法状态异常(e);
}
}
返回false;
}
电话:

Class clazz=Class.forName(className);
对象实例=clazz.newInstance();
设置(例如,“工资”,15);
集合(例如,“名字”、“约翰”);

仅供参考,以下是等效的通用getter:

@SuppressWarnings(“未选中”)
公共静态V get(对象对象,字符串字段名){
Class clazz=object.getClass();
while(clazz!=null){
试一试{
字段字段=clazz.getDeclaredField(字段名);
字段。setAccessible(true);
返回(V)字段。获取(对象);
}捕获(无此字段例外){
clazz=clazz.getSuperclass();
}捕获(例外e){
抛出新的非法状态异常(e);
}
}
返回null;
}
电话:

Class clazz=Class.forName(className);
对象实例=clazz.newInstance();
int salary=get(例如,“salary”);
String firstname=get(实例“firstname”);

更新名字

  • 首先找到要更新的字段
  • 然后找到mutator(它接受字段类型的参数)
  • 最后使用新值在对象上执行mutator:
Field-Field=classHandle.getDeclaredField(“firstName”);
方法setter=classHandle.getMethod(“setFirstName”,field.getType());
调用(myObject,“名字的新值”);
苹果包装;
导入java.lang.reflect.Field;
导入java.lang.reflect.Type;
导入java.util.Map.Entry;
导入java.util.Set;
导入com.google.gson.gson;
导入com.google.gson.JsonElement;
导入com.google.gson.JsonObject;
导入com.google.gson.JsonSyntaxException;
/*
*雇员详情类别
*/
班级员工{
私人长id;
私有字符串名称;
私有字符串用户名;
私人地址;
私人接触;
私人双薪;
公共长getId(){
返回id;
}
公共无效集合id(长id){
this.id=id;
}
公共字符串getName(){
返回名称;
}
公共void集合名(字符串名){
this.name=名称;
}
公共字符串getUserName(){
返回用户名;
}
public void setUserName(字符串用户名){
this.userName=用户名;
}
公共广播getAddress(){
回信地址;
}
公共无效设置地址(地址){
this.address=地址;
}
公共联系人getContact(){
回接;
}
公共联系人(联系人){
this.contact=contact;
}
公共双薪制{
返回工资;
}
公共收入(双倍工资){
这个。薪水=薪水;
}
}
/*
*雇员的地址类别
*/
班级地址{
私人城市;
私有字符串状态;
私人国家;
私有int pincode;
公共字符串getCity(){
回归城市;
}
公共城市(字符串城市){
this.city=城市;
}
公共字符串getState(){
返回状态;
}
公共无效设置状态(字符串状态){
this.state=状态;
}
公共字符串getCountry(){
返回国;
}
公共国家/地区(字符串国家/地区){
这个国家=国家;
}
公共int getPincode(){
返回pincode;
}
公共无效setPincode(int pincode){
this.pincode=pincode;
}
}
/*
*员工联系课程
*/
班级联系{
私人字符串电子邮件;
私有字符串contactNo;
公共字符串getEmail(){
回复邮件;
}
公用电子邮件(字符串电子邮件){
this.email=电子邮件;
}
公共字符串getContactNo(){
返回联系人号码;
}
public void setContactNo(字符串contactNo){
this.contactNo=contactNo;
}
}
公共类服务器{
公共静态void main(字符串args[])抛出JsonSyntaxException,异常{
Gson Gson=新的Gson();
/*
*旧员工数据
*/
地址=新地址();
触点=新触点();
员工=新员工();
地址:setCity(“shohna路”);
地址:setCountry(“印度”);
地址:setPincode(12201);
地址:setState(“哈里亚纳”);
contact.setContactNo(“+918010327919”);
contact.setEmail(“shivritesh9984@gmail.com");
employee.setAddress(地址);
employee.setContact(contact);
雇员身份证号码(4389573);
雇员名称(“RITESH SINGH”);
雇员工资(43578349.345);
employee.setUserName(“ritesh9984”);
System.out.println(“Employee:+gson.toJson(Employee));
/*新员工数据*/
员工emp=员工;
地址:setCity(“OMAX”);
emp.setAddress(地址);
emp.setName(“RAVAN”);
/*使用新员工对象更新员工*/
更新(employee,gson.fromJson(gson.toJson(emp),JsonObject.class));
System.out.println(“员工更新:+gson.toJson(员工));
}
/*
*此方法使用json对象形式的新对象的新给定值更新@target
*/
公共静态void更新(对象目标,JsonObject json)引发异常{
Gson Gson=新的Gs
public class Person {

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

    public void setFirstName(String FirstName) {
        this.FirstName = FirstName;
    }   
}
if (method.getName().matches("set[A-Z].*") {
  method.invoke(person,salary)
  // and so on
}
package apple;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Map.Entry;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;

/*
* Employe Details class
 */
class Employee {

   private long id;
   private String name;
   private String userName;
   private Address address;
   private Contact contact;
   private double salary;

   public long getId() {
     return id;
   }
   public void setId(long id) {
      this.id = id;
   }
   public String getName() {
     return name;
   }
   public void setName(String name) {
    this.name = name;
   }
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public Address getAddress() {
    return address;
}
public void setAddress(Address address) {
    this.address = address;
}
public Contact getContact() {
    return contact;
}
public void setContact(Contact contact) {
    this.contact = contact;
}
public double getSalary() {
    return salary;
}
public void setSalary(double salary) {
    this.salary = salary;
}
}

/*
 * Address class for employee
*/
class Address {

private String city;
private String state;
private String country;
private int pincode;

public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getState() {
    return state;
}
public void setState(String state) {
    this.state = state;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public int getPincode() {
    return pincode;
}
public void setPincode(int pincode) {
    this.pincode = pincode;
}

}

/*
 * Contact class for Employee
 */
 class Contact {

private String email;
private String contactNo;

public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getContactNo() {
    return contactNo;
}
public void setContactNo(String contactNo) {
    this.contactNo = contactNo;
}

}

public class Server {

public static void main(String args[]) throws JsonSyntaxException, Exception{
    Gson gson = new Gson();

    /*
     * Old Employee Data
     */
    Address address = new Address();
    Contact contact = new Contact();
    Employee employee = new Employee();
    address.setCity("shohna-road");
    address.setCountry("INDIA");
    address.setPincode(12201);
    address.setState("Hariyana");
    contact.setContactNo("+918010327919");
    contact.setEmail("shivritesh9984@gmail.com");
    employee.setAddress(address);
    employee.setContact(contact);
    employee.setId(4389573);
    employee.setName("RITESH SINGH");
    employee.setSalary(43578349.345);
    employee.setUserName("ritesh9984");
    System.out.println("Employee : "+gson.toJson(employee));

    /* New employee data */
    Employee emp = employee;
    address.setCity("OMAX");
    emp.setAddress(address);
    emp.setName("RAVAN"); 

    /* Update employee with new employee Object*/
    update(employee, gson.fromJson(gson.toJson(emp), JsonObject.class) );

    System.out.println("Employee-Update : "+gson.toJson(employee));
}

/*
 * This method update the @target with new given value of new object in json object form
 */
public static  void update(Object target, JsonObject json) throws Exception {
   Gson gson=new Gson();
   Class<? > class1 = target.getClass();

   Set<Entry<String, JsonElement>> entrySet = json.entrySet();
   for (Entry<String, JsonElement> entry : entrySet) {
       String key = entry.getKey();
       Field field = class1.getDeclaredField(key);
       field.setAccessible(true);
       Type genType = field.getGenericType();

       field.set(target,
               gson.fromJson(entry.getValue(),genType));
   }

   }

 }