Skip to content

Instantly share code, notes, and snippets.

@SINGHPRT
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save SINGHPRT/899b2f09ac9108436d5d to your computer and use it in GitHub Desktop.

Select an option

Save SINGHPRT/899b2f09ac9108436d5d to your computer and use it in GitHub Desktop.
Getting All fields(including inherited) from a JAVA class[POJO]
package com.pratap.utils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import org.apache.commons.lang3.ArrayUtils;
/**
* Utility methods for Data migration, Import, export etc.
*
* @author Pratap
*/
public class MigrationUtils {
static final Logger log = Logger.getLogger(MigrationUtils.class.getName());
static class ClassFinder{
public static final String[] packages = {
"com.pratap.package1",
"com.pratap.package2" };
public static Class<?> findClassByName(String name) {
for(int i=0; i<packages.length; i++){
try{
return Class.forName(packages[i] + "." + name);
} catch (ClassNotFoundException e){
//not in this package, try another
} catch (Exception e){
//deal with other problems...
}
}
//nothing found: return null or throw ClassNotFoundException
return null;
}
}
public static Map<String, String> getFieldCollectionInfo(String name) throws IllegalArgumentException, IllegalAccessException {
//Excluding JDO-specific fields
String[] excludedFields={"jdoDetachedState","jdoFieldFlags","jdoFieldNames","jdoFieldTypes","jdoFlags",
"jdoInheritedFieldCount","jdoPersistenceCapableSuperclass","jdoStateManager","serialVersionUID","key"};
Map<String, String> nameTypeMaps = new HashMap<>();
try{
Class<?> targetClass =ClassFinder.findClassByName(name);
if(targetClass!=null){
Field[] declaredFields = targetClass.getDeclaredFields();
Class<?> superClass=targetClass.getSuperclass();
while(superClass!=null){
declaredFields=ArrayUtils.addAll(declaredFields,superClass.getDeclaredFields());
superClass=superClass.getSuperclass();
}
for (Field field : declaredFields) {
if(ArrayUtils.contains(excludedFields,field.getName())){
continue;
}
field.setAccessible(true);
if(field.getType().isEnum()){
nameTypeMaps.put(field.getName(), "Enum");
}else{
nameTypeMaps.put(field.getName(), field.getType().getSimpleName());
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
return nameTypeMaps;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment