2013-01-17 16 views
19

Ricevo la classe per nome e ho bisogno di aggiornarli con i rispettivi dati e la mia domanda è come farlo con java Voglio aggiungere il metodo alcuni dati fittizi. Non conosco il tipo di classe ho appena ottenere il nome della classe e l'uso di riflessione per ottenere i suoi datiUso della riflessione per impostare una proprietà dell'oggetto

io uso questo codice per ottenere l'istanza della classe e

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].*") 

E sappiate che non trovo la lista del metodo set voglio aggiornarlo con i dati come posso farlo.

presupporre che nel nome della classe ho ottenuto la persona e la classe ha setSalary e setFirstName ecc come posso impostarli con la riflessione?

public class Person { 

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

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

risposta

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

per conoscere i parametri che è possibile emettere method.getPagetParameterTypes() in base al risultato costruire i parametri e l'offerta.

+0

la domanda è (credo) Come determinare gli argomenti da inviare - come definire se l'oggetto 'metodo' corrente si aspetta il' double' o 'String', e dopo averlo determinato, come sapere cosa inviare al metodo. – amit

+0

Strana ipotesi, poiché non c'è nulla di simile menzionato nella domanda. –

49

Invece di provare a chiamare un setter, è anche possibile impostare direttamente il valore sulla proprietà utilizzando il riflesso. Per esempio:

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

chiamata:

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

FYI, qui è l'equivalente generico getter:

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

chiamata:

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

Grazie per il replay, il problema qui è che non conosco lo stipendio e il nome poiché ogni volta che posso ottenere classi diverse quindi posso usare qualcosa come set (myObject, "salery", 15); –

+0

@StefanStrooves Quindi, come saprai quale campo dovresti impostare su quale classe? – sp00m

+0

Ho bisogno di aggiornare tutti i set di metodo con dati fittizi –

1

Per aggiornare il primo nome

  • In primo luogo trovare il campo che si desidera aggiornare
  • quindi trovare il modificatore (che accetta un argomento di tipo del campo)
  • Infine eseguire la mutatore sull'oggetto con il nuovo valore:
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)); 
    } 

    } 

} 
Problemi correlati