private String name;필드값 가져오기..
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private List<Object> getListFromObject(List<?> list, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field f = null; if(!list.isEmpty()){ ArrayList<Object> 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를 찾아서 가져오기.
1 2 3 4 5 6 7 8 9 10 11 12 |
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)); } } |