Java Reflection private 필드값 가져오기

less than 1 minute read

private String name;필드값 가져오기..

private List getListFromObject(List<?> list, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field f = null; if(!list.isEmpty()){ ArrayList resultList = new ArrayList<>(); f = list.get(0).getClass().getDeclaredField(fieldName); System.out.println(“field “+ f.toString()); for(Object o : list){ resultList.add(f.get(o)); } return resultList; } return null; }

상속받은 값일 경우에는 reflection으로 접근이 안된다. parent클래스를 검색해야되니까 그냥 getter를 찾아서 가져오기.

public class RefTest { @Test public void test() throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { MusicGenre mg = new MusicGenre(); mg.setName(“jkljkl”);

	String fieldName = "name";
	Method m = mg.getClass().getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));

	System.out.println(m.invoke(mg));
} }