How to get fields(variables) name and type of class using Reflection?
UPDATED: 27 April 2015
Tags:
Reflection
Reflection API is used to interact, examine or modify run-time behavior of programs running in the Java virtual machine. Reflection is bit costly so use it only when you have no other options left. Today we'll see how you can get name and type of fields(variables) declared in class.
Source Code
I've created some sample beans for example.
/* Actor.java */ import java.util.List; import java.util.Map; import java.util.Set; public class Actor { private long id; private String Name; private Set<Film> Films; private List<Language> LanguageSpeaks; private Map<string long=""> dummyMap; } /* Film.java */ public class Film { private long id; private String Name; } /* Language.java */ public class Language { private long id; private String Name; }
Source Code
import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; public class ClassFieldsReflection { public static void main(String[] args) { ClassFieldsReflection objClassFieldsReflection = new ClassFieldsReflection(); objClassFieldsReflection.AccessFieldsUsingReflection(new Actor()); } /** * Access fields of Object using Reflection. * @param obj */ private void AccessFieldsUsingReflection(Object obj){ /* Get array of fields declared in Class */ Field[] fields = obj.getClass().getDeclaredFields(); /* Loop through all fields */ for(int i = 0; i < fields.length ; i++){ /* Get field name */ String fieldName = fields[i].getName(); /* Get generic/base type of field (int, short, long, String, etc...) */ Object fieldType = fields[i].getGenericType(); System.out.println("Field(variable) name: " + fieldName); System.out.println("Generic Type: " + fieldType); /* Set<E>, List<E> and Map<K,V> are ParameterizedType */ if(fieldType instanceof ParameterizedType){ /** * This will give you Actual Type of Set<E>, List<E> and Map<K,V>. * Example: * List<String> -> String is ActualType * Set<Integer> -> Integer is ActualType * Map<String, Long> -> String, Long is ActualType */ System.out.println("Actual Type:"); for(Object objActualType : ((ParameterizedType) fieldType).getActualTypeArguments()){ System.out.println("-- "+objActualType); } } System.out.println("+++++++++++++++++++++++++++++++"); } } }
Output
Field(variable) name: id Generic Type: long +++++++++++++++++++++++++++++++ Field(variable) name: Name Generic Type: class java.lang.String +++++++++++++++++++++++++++++++ Field(variable) name: Films Generic Type: java.util.SetActual Type: -- class javaQuery.beans.Film +++++++++++++++++++++++++++++++ Field(variable) name: LanguageSpeaks Generic Type: java.util.List Actual Type: -- class javaQuery.beans.Language +++++++++++++++++++++++++++++++ Field(variable) name: dummyMap Generic Type: java.util.Map Actual Type: -- class java.lang.String -- class java.lang.Long +++++++++++++++++++++++++++++++
Tags:
Reflection
0 comments :