You can do with java reflection . For example we will take your sql query is like this.
SELECT FirstName 'FNAME', LastName 'LNAME', Grade 'GRADE' FROM Employee
So you will get the output as the following
FNAME LNAME GRADE
John Dan A+
Then in your java code you will need to reflection to achieve the rest
Suppose your Student class is like this
public class Student { private String LNAME; private String FNAME; private String GRADE; public String getLNAME() { return LNAME; } public void setLNAME(String lNAME) { LNAME = lNAME; } public String getFNAME() { return FNAME; } public void setFNAME(String fNAME) { FNAME = fNAME; } public String getGRADE() { return GRADE; } public void setGRADE(String gRADE) { GRADE = gRADE; } }
And you can set the corresponding values in the Student class using the following code.
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; public class Main { public static void main(String[] args) { try { //configuring the columns in the sql statement and class String[] ColumnArray = new String[]{"LNAME","FNAME","GRADE"}; // making a hashmap to emulate the result set of sql HashMap<String, String> rs = new HashMap<String, String>(); rs.put("FNAME", "John"); rs.put("LNAME", "Dan"); rs.put("GRADE", "A+"); //reflection of the Class cls = Class.forName("Student"); Object c = cls.newInstance(); Method[] mtd = cls.getMethods(); for (String column : ColumnArray) { Method method = cls.getMethod("set"+column, String.class); method.invoke(c, new Object[]{rs.get(column)}); } //casting the class to employee Student student = (Student) c; //Printing the output System.out.println(student.getFNAME()); System.out.println(student.getLNAME()); System.out.println(student.getGRADE()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); }catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }}
Please let me know if your facing any issue. Happy to help you.