Skip to content

Instantly share code, notes, and snippets.

@dpr-odoo
Created June 24, 2014 03:16
Show Gist options
  • Save dpr-odoo/4097fe16517d94b1f455 to your computer and use it in GitHub Desktop.
Save dpr-odoo/4097fe16517d94b1f455 to your computer and use it in GitHub Desktop.
Java Field Reflection - Getting non-null fields value using reflection
/**
* Java Field Reflection
* Getting non-null members (fields) value from parent class using Java Reflection
*
* @author Dharmang Soni <dpr@odoo.com>
*/
package com.reflection;
import java.lang.reflect.Field;
public class JavaFieldReflection {
public static void main(String[] args) {
ChildClass c = new ChildClass();
c.test();
}
}
class ChildClass extends BaseTest {
protected String name = "Parth Gajjar";
protected String city = null;
private Person person = new Person("Dharmang Soni", "Gandhinagar");
}
class BaseTest {
public void test() {
// Getting BaseTest class
Class<?> c = getClass();
// Looping all fields in current class
for (Field f : c.getDeclaredFields()) {
// Required true if you want to access its private members
f.setAccessible(true);
// field name
System.out.print("[Field : " + f.getName());
// Field type
System.out.print(", Type : " + f.getType().getName());
try {
// Getting instance value (because of we extend BaseTest to our
// ChildClass we uses "this" in Field.get()"
Object object = f.get(this);
// Checking for null assignment
if (object == null) {
System.out.print(", Value : null");
}
// Checking for String type
if (object instanceof String) {
System.out.print(", Value : " + object);
}
// Checking for Person class
if (object instanceof Person) {
Person col = (Person) f.get(this);
System.out.print(", Name: " + col.getName() + ", City: "
+ col.getCity());
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.print("]\n");
}
}
}
class Person {
String name, city;
public Person(String name, String city) {
super();
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment