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

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *