4,511,109 th visitor since 2017.2.1 ( Today : 1676 )
Programming
No. 766
Name. swindler
Subject. java reflection
Main Cate. Java
Sub Cate.
Date. 2014-03-05 09:47
Hit. 3169 (211.36.27.3)
File.
import java.lang.reflect.Field


필드명을 가져오는 방법

Class _class = ChampionDto.class;

Field[] fields = _class.getDeclaredFields();

for ( int i = 0; i < fields.length; i++ )
{
System.out.println(fields[i].getName());
}

여기서 getFields를 사용하면 public fields 만 가져오게 된다.


===중략


Test test = new Test(); //필드가 포함되어 있는 class
Field fd = test.getClass().getDeclaredField("필드명");


//"필드명"의 값 가져오기
String testFieldVal = (String)fd.get(test); //필드 객체의 get 함수에 class 객체를 넘기고
//해당 변수의 형으로 캐스팅



import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class Reflective {

public void message(String choice) throws NoSuchMethodException, NullPointerException, SecurityException, IllegalAccessException, InvocationTargetException {
this.getClass().getDeclaredMethod(choice, (Class[]) null).invoke(this);
}

public void hello() {
System.out.println("hello");
}

public static void main(String[] args) {
try {
Reflective r = (Reflective) Class.forName("Reflective").newInstance();
r.message("hello");
} catch (NoSuchMethodException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SecurityException e) {
System.out.println(e);
} catch (InstantiationException e) {
System.out.println(e);
} catch (IllegalAccessException e) {
System.out.println(e);
} catch (InvocationTargetException e) {
System.out.println(e);
}
}
}


JavaDoc Link


[바로가기 링크] : http://coolx.net/cboard/develop/766


Name
Password
Comment
Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

  2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog