Getting null from getters method - java

I am getting null from getters method when trying to save it in a list and calling the list in servlet. Please help me out to get rid of this. Thanks in advance.
I am adding first the getters and setters method code then DAO code and then servlet code.
package com.vechile.model;
public class DriverSearchResult {
private String Id;
private String Name;
private String Address;
private String City;
private String Contact;
private String Country;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getContact() {
return Contact;
}
public void setContact(String contact) {
Contact = contact;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
package com.vechile.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.vechile.model.Driver;
import com.vechile.model.DriverSearchResult;
import com.vechile.model.Searching;
import com.vechile.utils.DBConnection;
public class SearchDAO {
private String sql;
private ResultSet rs, rs1;
public boolean searchDriver(Searching searching) {
try {
sql = String.format("select * from adddriver where (%s) = '%s'",
searching.getInputList(), searching.getTxtField());
rs = DBConnection.executeQuery(sql);
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
Integer id = new Integer(rs.getInt(1));
String stringID = id.toString();
setResult.setId(stringID);
setResult.setName(rs.getString(1));
setResult.setAddress(rs.getString(2));
setResult.setCity(rs.getString(3));
setResult.setContact(rs.getString(4));
setResult.setCountry(rs.getString(5));
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
List<DriverSearchResult> returnList = new ArrayList<DriverSearchResult>();
DriverSearchResult getResult = new DriverSearchResult();
String id = getResult.getId();
String name = getResult.getName();
String address = getResult.getAddress();
String city = getResult.getCity();
String contact = getResult.getContact();
String country = getResult.getCountry();
returnList.add(getResult);
return returnList;
}
public boolean searchBooking(Searching searching) {
try {
sql = String.format(
"select * from booking where booking_id = '%s'",
searching.getBookingSearch());
rs1 = DBConnection.executeQuery(sql);
if (rs1.next()) {
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String input = request.getParameter("list");
String txtField = request.getParameter("txtField");
String op = request.getParameter("op");
String bSearch = request.getParameter("bookingSearch");
try{
if(op.equals("1")){
Searching search1 = new Searching();
search1.setInputList(input);
search1.setTxtField(txtField);
SearchDAO searchDAO = new SearchDAO();
boolean searchDriver = searchDAO.searchDriver(search1);
if(searchDriver){
DriverSearchResult searchResult = new DriverSearchResult();
System.out.println(searchResult.getId());
//response.sendRedirect("driversearchresult.jsp");
//response.sendRedirect("SearchOutPut.jsp?op=" + search1.getPassingValue());
}
else {
out.println("<html>");
out.println("<head>");
out.println("<script>");
out.println("alert('Record Not Found!')");
out.println("</script>");
out.println("<META HTTP-EQUIV= Refresh CONTENT=0;URL=SearchDriver.jsp>");
}
}

That happens because you fill DriverSearchResult object in the method searchDriver and then forget that object. Then in another method you create another instance of class DriverSearchResult and try to extract values from it without prior initialization. That's why it gives you nulls, since you never call setters on this newly created instance.
I guess you want to save DriverSearchResult instance created in searchDriver method and then use it in other methods instead of creating new one.
UPD:
I hope the idea is clear from the code snippet:
public class SearchDAO {
private List<DriverSearchResult> resultList = new ArrayList<>();
public boolean searchDriver(Searching searching) {
try {
// ...
if(rs.next()) {
DriverSearchResult setResult = new DriverSearchResult();
// ...
resultList.add(setResult); // <<<<<<<<<
return true;
}
} catch (Exception e) {
e.getStackTrace();
}
return false;
}
public List<DriverSearchResult> getDriverResult(){
return resultList; // <<<<
}
}

Related

When I try to add a Object into an ArrayList, it add the hashcode, don't know how to solve. Beginner [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 3 years ago.
That's my code, never had this problem before...
Tried with toString and ArrayList<String> too but it still printing the hashcode. I want something like a JSON, thought ArrayList was supposed to do it automatically.
I want my select into an ArrayList.
output is:
[com.firebirdangularjs.ws.rest.paises.Paises#49e4cb85, com.firebirdangularjs.ws.rest.paises.Paises#2133c8f8, com.firebirdangularjs.ws.rest.paises.Paises#43a25848]
package testebd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.ResultSet;
import com.firebirdangularjs.ws.rest.paises.Paises;
public class TesteDoBDAngularJS {
public static void main(String[] args) {
ArrayList<Paises> listaPaises= new ArrayList<Paises>();
try {
Class.forName("org.firebirdsql.jdbc.FBDriver");
Connection con = DriverManager.getConnection("jdbc:firebirdsql:localhost/3050:C:\\Exercicio_Banco\\UNICAMBIO_AVS.FDB?encoding=ISO8859_1","sysdba", "password");
Statement st = con.createStatement();
String Query = "SELECT * FROM CMBPESPAIS WHERE PAISCODIGO >= 244 ";
System.out.println(Query + "\n\n\n");
ResultSet rs = st.executeQuery(Query);
rs.next();
do {
String paisCodigo = rs.getString(1);
String nome = rs.getString(2);
String bacenCodigo = rs.getString(3);
String nacionalidade = rs.getString(4);
String coafPaisRestrito = rs.getString(5);
String codigoDeSegUsu = rs.getString(6);
String usudt = rs.getString(7);
String siglaIso = rs.getString(8);
String siglaIsoTr = rs.getString(9);
Paises pais = new Paises(paisCodigo, nome, bacenCodigo, nacionalidade, coafPaisRestrito, codigoDeSegUsu, usudt, siglaIso, siglaIsoTr);
listaPaises.add(pais);
} while (rs.next());
} catch(Exception e){
System.out.println("OPS! Something went wrong...");
System.out.println(e.getMessage());
}
System.out.println(listaPaises);
}
}
package com.firebirdangularjs.ws.rest.paises;
public class Paises {
private String NOME, NACIONALIDADE, COAFPAISRESTRITOSN, SIGLAISO, SIGLAISO3, BACENCODIGO, SEGURANCAUSUARIOCODIGO, USUARIODATAHORA, PAISCODIGO;
public Paises(String paisCodigo2, String nOME, String bACENCODIGO, String nACIONALIDADE, String cOAFPAISRESTRITOSN,String sEGURANCAUSUARIOCODIGO, String dataUsu, String sIGLAISO, String sIGLAISO3) {
super();
this.NOME = nOME;
this.NACIONALIDADE = nACIONALIDADE;
this.COAFPAISRESTRITOSN = cOAFPAISRESTRITOSN;
this.SIGLAISO = sIGLAISO;
this.SIGLAISO3 = sIGLAISO3;
this.BACENCODIGO = bACENCODIGO;
this.SEGURANCAUSUARIOCODIGO = sEGURANCAUSUARIOCODIGO;
this.PAISCODIGO = paisCodigo2;
this.USUARIODATAHORA = dataUsu;
}
public String getPAISCODIGO() {
return PAISCODIGO;
}
public void setPAISCODIGO(String pAISCODIGO) {
PAISCODIGO = pAISCODIGO;
}
public String getNOME() {
return NOME;
}
public void setNOME(String nOME) {
NOME = nOME;
}
public String getNACIONALIDADE() {
return NACIONALIDADE;
}
public void setNACIONALIDADE(String nACIONALIDADE) {
NACIONALIDADE = nACIONALIDADE;
}
public String getCOAFPAISRESTRITOSN() {
return COAFPAISRESTRITOSN;
}
public void setCOAFPAISRESTRITOSN(String cOAFPAISRESTRITOSN) {
COAFPAISRESTRITOSN = cOAFPAISRESTRITOSN;
}
public String getSIGLAISO() {
return SIGLAISO;
}
public void setSIGLAISO(String sIGLAISO) {
SIGLAISO = sIGLAISO;
}
public String getSIGLAISO3() {
return SIGLAISO3;
}
public void setSIGLAISO3(String sIGLAISO3) {
SIGLAISO3 = sIGLAISO3;
}
public String getBACENCODIGO() {
return BACENCODIGO;
}
public void setBACENCODIGO(String bACENCODIGO) {
BACENCODIGO = bACENCODIGO;
}
public String getSEGURANCAUSUARIOCODIGO() {
return SEGURANCAUSUARIOCODIGO;
}
public void setSEGURANCAUSUARIOCODIGO(String sEGURANCAUSUARIOCODIGO) {
SEGURANCAUSUARIOCODIGO = sEGURANCAUSUARIOCODIGO;
}
public String getUSUARIODATAHORA() {
return USUARIODATAHORA;
}
public void setUSUARIODATAHORA(String uSUARIODATAHORA) {
USUARIODATAHORA = uSUARIODATAHORA;
}
}
You must override toString() function and give it expected output implementation in class Paises to achieve the objective.
Example :
class Paises {
private String paramA;
private String paramB;
.....
public String toString(){
return paramA + " " + paramB.....;
}
}

Input 3 Attributes Into HashMap Key

I am new to Java. I am now using HashMap for the purpose to store data from MySQL database and I will use the JSon POST request to get the input from user and search for the related data in the HashMap and retrieve from the HashMap. I need three inputs from the user but in the HashMap only able to input 1 key. So, I tried the way to input the key as an object but it is not working. Below is my code for storing data from MySQL database.
public class AppDataService {
HashMap<AppDataRequest, AppData> appdatas = new HashMap<AppDataRequest, AppData>();
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://****:3306/****_demo";
static final String USER = "****";
static final String PASS = "****";
public AppDataService(){
Connection conn = null;
Statement stat = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stat = conn.createStatement();
String sql = "SELECT * FROM testdata";
ResultSet resu = stat.executeQuery(sql);
while(resu.next()){
int id = resu.getInt("app_id");
String email = resu.getString("email");
String password = resu.getString("password");
String status = resu.getString("status");
String message = resu.getString("message");
String token = resu.getString("token");
appdatas.put(new AppDataRequest(id, email, password), new AppData(status, message, token));
}
resu.close();
stat.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(stat!=null){
stat.close();
}
}
catch (SQLException se2){
}
try{
if(conn!=null){
conn.close();
}
}
catch(SQLException se3){
se3.printStackTrace();
}
}
}
public List<AppData> getAllAppData(){
return new ArrayList<AppData>(appdatas.values());
}
public AppData getAppData(int id){
return appdatas.get(id);
}
public AppData getSAppData(int id, String email, String password){
return appdatas.get(new AppDataRequest (id, email, password));
}
}
My JSon POST code
#Path("/appdata")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
AppDataService ads = new AppDataService();
#POST
#Path("/appdatas")
public AppData getSAppData(AppDataRequest adr){
return ads.getSAppData(adr.getId(), adr.getEmail(),adr.getPassword());
}
AppData Class
public class AppData {
public String status;
public String message;
public String token;
public AppData(){
}
public AppData(String status, String message, String token) {
this.status = status;
this.message = message;
this.token = token;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
AppDataRequest Class
public class AppDataRequest {
public int id;
public String email;
public String password;
public AppDataRequest(){
}
public AppDataRequest(int id, String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
You can overide hashCode and equals in your class :
#Override
public int hashCode() {
int hash = 3;
hash = 83 * hash + this.id;
hash = 83 * hash + Objects.hashCode(this.email);
hash = 83 * hash + Objects.hashCode(this.password);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AppDataRequest other = (AppDataRequest) obj;
if (this.id != other.id) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.password, other.password)) {
return false;
}
return true;
}
Why you don't make the id like a key if it is unique in your table, and your other information as value of map :
Map<Integer, AppData> appdatas;
appdatas.put(id, new AppData(status, message, token, email, password));
HashMap internally makes use of HashCode and Equals method to insert and retrieve the Object from the collection.
You need to override the equals() and Hashcode() method in Java to use a Custom Object as Key within a HashMap. Also it is preferred to have an Immutable Class as a Key which again you have to consider.
Have a look at below
What issues should be considered when overriding equals and hashCode in Java?
If not you can always use the Standard String/Wrapper Classes as Key as they by default provide the methods and design necessary to use.
As Further Reading look for how HashMap Works and you will understand why.
Hope this helps.

How do I return an object when I only have access to one field of it?

Sorry if this doesn't make sense, I can't think of a better way to phrase it. Hopefully my code illustrates my problem better.
So in this method I want to return a Myuser object. A Myuser object has about 8 string fields, one of which is userId.
As you can see, when this method is called, a string is passed in. If this string has the same value as the userId field in the Myuser object, then I want it to return the full Myuser object. Otherwise it returns null.
public Myuser getRecord(String userId) {
Connection cnnct = null;
PreparedStatement pStmnt = null;
Myuser myusr = null;
boolean result = false;
try {
cnnct = getConnection();
String preQueryStatement = "SELECT * FROM MYUSER WHERE USERID = ?";
pStmnt = cnnct.prepareStatement(preQueryStatement);
pStmnt.setString(1, userId);
ResultSet rslt = pStmnt.executeQuery();
result = rslt.next();
if (result) {
//return myusr in its entirety
}
} catch (SQLException ex) {
while (ex != null) {
ex.printStackTrace();
ex = ex.getNextException();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (pStmnt != null) {
try {
pStmnt.close();
} catch (SQLException e) {
}
}
if (cnnct != null) {
try {
cnnct.close();
} catch (SQLException sqlEx) {
}
}
}
return myusr;
}
Edit: I thought for the heck of it I would post the Myuser class as well.
public class Myuser {
private String userid;
private String name;
private String password;
private String email;
private String phone;
private String address;
private String secQn;
private String secAns;
public Myuser(String userid, String name, String password, String email, String phone, String address, String secQn, String secAns) {
this.userid = userid;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.address = address;
this.secQn = secQn;
this.secAns = secAns;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecQn() {
return secQn;
}
public void setSecQn(String secQn) {
this.secQn = secQn;
}
public String getSecAns() {
return secAns;
}
public void setSecAns(String secAns) {
this.secAns = secAns;
}
}
You can easily use result.getXXX(field_name):
if (rslt.next()) {
myusr = new Myuser(result.getString("userid"), result.getString("name"),
result.getString("password"), result.getString("phone"),
...);
}
Note don't need to use result = rslt.next(); before if(result), you have to use directly
if (rslt.next()) {
...
}

Storing an arraylist of custom objects (which have Strings, Dates, Lists, and more as fields) in shared preferences

I am trying to save an arraylist of clients in shared preferences, however I am getting out of memory error. I am new to this and can't figure out how to do this? I looked at a lot of pages on stackoverflow, but couldn't find one that would work for me or that also had an ArrayList of custom objects, where every object contains more ArrayLists with custom objects.
client object:
public class Client implements Serializable, Comparable<Client> {
private int clientID;
private String name;
private String phone;
private String email;
private String url;
private Double turnover;
private String visitAddress;
private String visitCity;
private String visitZipcode;
private String visitCountry;
private String postalAddress;
private String postalCity;
private String postalZipcode;
private String postalCountry;
private Drawable clientImage;
private List<Contact> contactList = new ArrayList<Contact>();
private List<Project> projectList = new ArrayList<Project>();
private List<Task> taskList = new ArrayList<Task>();
private List<Order> orderList = new ArrayList<Order>();
public Client(int clientID, String Name, String Phone, String Email, String URL, Double Turnover,
String VisitAddress, String VisitCity, String VisitZipcode, String VisitCountry,
String PostalAddress, String PostalCity, String PostalZipcode, String PostalCountry,
List contactList, List projectList, List taskList, List orderList){
super();
this.clientID = clientID;
this.name = Name;
this.phone = Phone;
this.email = Email;
this.url = URL;
this.turnover = Turnover;
this.visitAddress = VisitAddress;
this.visitCity = VisitCity;
this.visitZipcode = VisitZipcode;
this.visitCountry = VisitCountry;
this.postalAddress = PostalAddress;
this.postalCity = PostalCity;
this.postalZipcode = PostalZipcode;
this.postalCountry = PostalCountry;
this.contactList = contactList;
this.projectList = projectList;
this.taskList = taskList;
this.orderList = orderList;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
public String getEmail() {
return email;
}
public String getUrl() {
return url;
}
public Double getTurnover() {
return turnover;
}
public String getVisitAddress() {
return visitAddress;
}
public String getVisitCity() {
return visitCity;
}
public String getVisitZipcode() {
return visitZipcode;
}
public String getVisitCountry() {
return visitCountry;
}
public String getPostalAddress() {
return postalAddress;
}
public String getPostalCity() {
return postalCity;
}
public String getPostalZipcode() {
return postalZipcode;
}
public String getPostalCountry() {
return postalCountry;
}
public List<Contact> getContactList(){
return contactList;
}
public List<Project> getProjectList(){
return projectList;
}
public List<Task> getTaskList(){
return taskList;
}
public List<Order> getOrderList() {
return orderList;
}
public void setName(String name) {
this.name = name;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEmail(String email) {
this.email = email;
}
public void setUrl(String url) {
this.url = url;
}
public void setTurnover(Double turnover) {
this.turnover = turnover;
}
public void setVisitAddress(String visitAddress) {
this.visitAddress = visitAddress;
}
public void setVisitCity(String visitCity) {
this.visitCity = visitCity;
}
public void setVisitZipcode(String visitZipcode) {
this.visitZipcode = visitZipcode;
}
public void setVisitCountry(String visitCountry) {
this.visitCountry = visitCountry;
}
public void setPostalAddress(String postalAddress) {
this.postalAddress = postalAddress;
}
public void setPostalCity(String postalCity) {
this.postalCity = postalCity;
}
public void setPostalZipcode(String postalZipcode) {
this.postalZipcode = postalZipcode;
}
public void setPostalCountry(String postalCountry) {
this.postalCountry = postalCountry;
}
public Drawable getClientImage() {
return clientImage;
}
public void setClientImage(Drawable clientImage) {
this.clientImage = clientImage;
}
public int getClientID() {
return clientID;
}
public void setClientID(int clientID) {
this.clientID = clientID;
}
underlying project object: (also with list of custom objects)
public class Project implements Serializable, Comparable<Project>{
private String clientName;
private String projectName;
private String projectDiscription;
private String projectStatus;
private GregorianCalendar projectDate;
private List<TimeSheet> projectTimeRegestrationList = new ArrayList<>();
private List<WorkOrder> workOrderList = new ArrayList<WorkOrder>();
public Project(String clientName, String projectName, String projectDiscription, String projectStatus, GregorianCalendar projectDate, List projectTimeRegestrationList, List workOrderList) {
this.projectName = projectName;
this.projectDiscription = projectDiscription;
this.projectStatus = projectStatus;
this.projectDate = projectDate;
this.clientName = clientName;
this.projectTimeRegestrationList = projectTimeRegestrationList;
this.workOrderList = workOrderList;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDiscription() {
return projectDiscription;
}
public void setProjectDiscription(String projectDiscription) {
this.projectDiscription = projectDiscription;
}
public String getProjectStatus() {
return projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public GregorianCalendar getProjectDate() {
return projectDate;
}
public void setProjectDate(GregorianCalendar projectDate) {
this.projectDate = projectDate;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public List<TimeSheet> getProjectTimeRegestrationList() {
return projectTimeRegestrationList;
}
public List<WorkOrder> getWorkOrderList() {
return workOrderList;
}
now my specific question: is it possible to save this inside shared preferences, if yes, how do i do this, if no, how should i then locally safe this data.
you can use json to store them as a string in sharedpreference
for example if you want to store an object of your client class contaning a url ,country and phone
just write the following
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
jsonArray.put(object1);
//adding another object
JSONObject object2=new JSONObject();
object2.put("url","anotherurl");
object2.put("phone","anotherphonenumber");
object2.put("country","anothercountry");
jsonArray.put(object2);
} catch (JSONException e) {
e.printStackTrace();
}
and than simply save it as a string by calling jsonArray.toString() in sharedpreference
and if your object that you want to store contains a list of another object you can easily save like for example if you have a url, country, and phone number which you want to save plus a list of another object containing the first and lastname you can save list as json object itself just like you did for the url,phone number and country as shown below
try {
JSONArray jsonArray=new JSONArray();
JSONObject object1=new JSONObject();
object1.put("url","myurl");
object1.put("phone","myphonenumber");
object1.put("country","mycountry");
//saving a list of another object contaning firstname and lastname
JSONArray listArray=new JSONArray();
//supposing your list contains 10 objects
for(int f=0;f<10;f++){
JSONObject listobject=new JSONObject();
listobject.put("firstname","myfirstname");
listobject.put("lastname","mylastname");
listArray.put(listobject);
}
//now the list array we added as an object of the jsonArray variable
JSONObject object2=new JSONObject(); //object2 containing the list of firstname and lastname
object2.put("list",listArray.toString());
jsonArray.put(object1);//object1 contains the url, phone, and country
jsonArray.put(object2);//object2 contains the list of firstname and lastname
} catch (JSONException e) {
e.printStackTrace();
}

Using reflection to set an object property

I getting class by name and i need to update them with respective data and my question is how to do it with java
I want to add the method some dummy data .
I don't know the class type I just getting the class name and use reflection to get his data
I use this code to get the class instance and
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].*")
And know that I find the list of the set method I want to update it with data
how can I do that .
assume that In class name I got person and the class have setSalary and setFirstName etc
how can I set them with reflection ?
public class Person {
public void setSalery(double salery) {
this.salery = salery;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
}
Instead of trying to call a setter, you could also just directly set the value to the property using reflection. For example:
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;
}
Call:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "salary", 15);
set(instance, "firstname", "John");
FYI, here is the equivalent generic 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;
}
Call:
Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
int salary = get(instance, "salary");
String firstname = get(instance, "firstname");
To update the first name
First find the field you want to update
Then find the mutator (which accepts an argument of the field's type)
Finally execute the mutator on the object with the new value:
Field field=classHandle.getDeclaredField("firstName");
Method setter=classHandle.getMethod("setFirstName", field.getType());
setter.invoke(myObject, "new value for first name");
if (method.getName().matches("set[A-Z].*") {
method.invoke(person,salary)
// and so on
}
to know the parameters you can issue method.getPagetParameterTypes()
based on the result construct your parameters and supply.
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));
}
}
}

Categories

Resources