java/reflection (rev. 1.10)
설명 ¶
- 현재 프로젝트내의 클래스가 아닌 외부 패키지 클래스의 메소드를 호출하는 방법.
- 외부 프로젝트는 jar로 패키징 해야한다.
코드 ¶
~java
/**
* just print "say Hello" string to console
*/
public class HelloWorld {
public void sayHello() {
System.out.println("say Hello");
}
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
helloWorld.sayHello();
}
}
~java
/**
* call say HelloWorld class in external jar file package
*/
public class TestReflection {
public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
ClassLoader classLoader = Test.class.getClassLoader();
System.out.println(classLoader.getClass().getName());
URLClassLoader urlClassLoader = new URLClassLoader(
new URL[]{
new URL("file:/Users/fharenheit/Projects/openflamingo/helloworld.jar")
}, classLoader
);
System.out.println(Thread.currentThread().getContextClassLoader().getClass().getName());
Thread.currentThread().setContextClassLoader(urlClassLoader);
System.out.println(Thread.currentThread().getContextClassLoader().getClass().getName());
Class<?> helloWorld = ClassUtils.getClass("HelloWorld");
Object object = helloWorld.newInstance();
Method[] declaredMethods = helloWorld.getDeclaredMethods();
for (int i = 0; i < declaredMethods.length; i++) {
Method declaredMethod = declaredMethods[i];
System.out.println(declaredMethod.getName());
}
Method sayHello = o.getClass().getMethod("sayHello", null);
sayHello.invoke(object, null);
}
}