2013-01-17 211 views
19

我按類名獲得類,我需要使用各自的數據更新它們,我的問題是如何使用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].*") 

,知道我找到列表我想用數據更新它的設置方法 我該怎麼做。

假設在類名中我得到了人和類有setSalary和setFirstName等 我怎樣才能用反射來設置它們?

public class Person { 

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

    public void setFirstName(String FirstName) { 
     this.FirstName = FirstName; 
    } 
} 

回答

1
if (method.getName().matches("set[A-Z].*") { 
    method.invoke(person,salary) 
    // and so on 
} 

知道你可以根據結果構建你的參數和供應的問題method.getPagetParameterTypes() 的參數。

+0

的問題是,(我認爲)如何確定要發送的參數 - 如何定義當前的'method'對象是否期望double或String,並在確定之後 - 如何知道要發送給方法的內容。 – amit

+0

奇怪的假設,因爲這個問題中沒有提到這種類型。 –

49

而不是試圖調用setter,你也可以直接使用反射設置值的屬性。例如:

public static boolean set(Object object, String fieldName, Object fieldValue) { 
    Class<?> clazz = object.getClass(); 
    while (clazz != null) { 
     try { 
      Field field = clazz.getDeclaredField(fieldName); 
      field.setAccessible(true); 
      field.set(object, fieldValue); 
      return true; 
     } catch (NoSuchFieldException e) { 
      clazz = clazz.getSuperclass(); 
     } catch (Exception e) { 
      throw new IllegalStateException(e); 
     } 
    } 
    return false; 
} 

電話:

Class<?> clazz = Class.forName(className); 
Object instance = clazz.newInstance(); 
set(instance, "salary", 15); 
set(instance, "firstname", "John"); 

僅供參考,這裏是相當於通用吸氣

@SuppressWarnings("unchecked") 
public static <V> V get(Object object, String fieldName) { 
    Class<?> clazz = object.getClass(); 
    while (clazz != null) { 
     try { 
      Field field = clazz.getDeclaredField(fieldName); 
      field.setAccessible(true); 
      return (V) field.get(object); 
     } catch (NoSuchFieldException e) { 
      clazz = clazz.getSuperclass(); 
     } catch (Exception e) { 
      throw new IllegalStateException(e); 
     } 
    } 
    return null; 
} 

電話:

Class<?> clazz = Class.forName(className); 
Object instance = clazz.newInstance(); 
int salary = get(instance, "salary"); 
String firstname = get(instance, "firstname"); 
+0

感謝您的回放,這裏的問題是我不知道薪水和名字,因爲每次我可以獲得不同的課程,因此我可以使用set(myObject,「salery」,15)等類似的東西。 –

+0

@StefanStrooves那麼你怎麼知道你應該在哪個課上設置哪個領域? – sp00m

+0

我需要用dummy數據更新所有set方法 –

1

要更新的第一個名字

  • 首先找到你想更新
  • 然後找到突變(它接受該字段的類型的參數)
  • 最後執行與對象上的突變場新值:
Field field=classHandle.getDeclaredField("firstName"); 
Method setter=classHandle.getMethod("setFirstName", field.getType()); 
setter.invoke(myObject, "new value for first name"); 
0
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("[email protected]"); 
    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)); 
    } 

    } 

}