Get all variable name in Java
In this example, I am sharing simple program about, How to get all variable name in Java. The program were tested and output shared in the post.
1) Simple POJO(plain old java object) class
package com.dineshkrish; public class Customer { private int custId; private String custName; private String custAddress; private int custAge; public int getCustId() { return custId; } public void setCustId(int custId) { this.custId = custId; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustAddress() { return custAddress; } public void setCustAddress(String custAddress) { this.custAddress = custAddress; } public int getCustAge() { return custAge; } public void setCustAge(int custAge) { this.custAge = custAge; } }
2) Getting all name from particular class using java reflection
package com.dineshkrish; import java.lang.reflect.Field; /** * * @author Dinesh Krishnan * */ public class PrivateFieldList { public static void main(String[] args) { try { // Fully qualified class name Class<?> c = Class.forName("com.dineshkrish.Customer"); // getting the fields Field[] fields = c.getDeclaredFields(); // iterating the fields if(fields != null && fields.length > 0) { for (int i = 0; i < fields.length; i++) { System.out.println(fields[i].getName()); } } } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } }
Output
—-
custId
custName
custAddress
custAge
Refrences
1. Java Reflection API
2. Java Field API
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet