-- 입력받는 파라미터가 없는 메서드
import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; import java.lang.reflect.Method; import org.junit.Test; public class ReflectTest { @Test public void testReflect() throws Exception { Method method = Sample.class.getMethod("getSample"); assertThat((String) method.invoke(Sample.class.newInstance()), is("Sample")); } public static class Sample { public String getSample() { return "Sample"; } public String getSample(String append) { return "Sample " + append; } } }
-- 파라미터를 입력받는 메서드
import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; import java.lang.reflect.Method; import org.junit.Test; public class ReflectTest { @Test public void testReflect() throws Exception { Method method = Sample.class.getMethod("getSample"); assertThat((String) method.invoke(new Sample()), is("Sample")); method = Sample.class.getMethod("getSample", String.class); assertThat((String)method.invoke(new Sample(), "Test"), is("Sample Test")); } public class Sample { public String getSample() { return "Sample"; } public String getSample(String append) { return "Sample " + append; } } }
-- 다수의 파라미터를 받는 메서드
import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; import java.lang.reflect.Method; import org.junit.Test; public class ReflectTest { @Test public void testReflect() throws Exception { Method method = Sample.class.getMethod("getSample"); assertThat((String) method.invoke(new Sample()), is("Sample")); method = Sample.class.getMethod("getSample", String.class); assertThat((String)method.invoke(new Sample(), "Test"), is("Sample Test")); method = Sample.class.getMethod("getSample", String.class, int.class); assertThat((String)method.invoke(new Sample(), "Cut", 7), is("Cut")); } public class Sample { public String getSample() { return "Sample"; } public String getSample(String append) { return "Sample " + append; } public String getSample(String append, int beginIndex){ return getSample(append).substring(beginIndex); } } }
'Spring' 카테고리의 다른 글
jsp 에서 applicationcontext 얻어와서 getBean 사용하기. (0) | 2012.11.13 |
---|---|
[Spring] java.lang.reflect.Proxy 다이나믹 프록시 테스트 (0) | 2012.11.06 |