U E D R , A S I H C RSS

java/reflection

μ„λͺ…

  • classpathλΌ μ΄μš©ν•΄ ν˜„μž¬ ν”„λ‘œμ νŠΈλ‚΄μ˜ classκ°€ μ•„λ‹Œ μ™ΈλΆ€ νŒ¨ν‚€μ§€ class의 methodλΌ ν˜ΈμΆœν•˜λŠ” 방법.
  • μ™ΈλΆ€ ν”„λ‘œμ νŠΈλŠ” jar둜 νŒ¨ν‚€μ§• ν•œλ‹€.
  • jarνŒŒμΌμ— μ‘΄μž¬ν•˜λŠ” classλΌ ν˜„μž¬ ν”„λ‘œμ νŠΈμ—μ„œ λ™μ μœΌλ‘œ ν˜ΈμΆœν•  수 μžˆλ‹€.
    • ν”„λ ˆμž„μ›Œν¬μ—μ„œ 많이 μ‚¬μš©λ˜λŠ” 방법이라고 ν•œλ‹€.
    • ORM(Object-Relational-MApping)이 μ•„λ‹Œ λ°©μ‹μœΌλ‘œ DAOλΌ λ§Œλ“€ λ•Œ μ‚¬μš©λ˜κΈ°λ„ ν•œλ‹€.

μ½”λ“œ

  • λ¬Έμžμ—΄μ„ 좜λ ₯ν•˜λŠ” μƒ˜ν”Œ 클래슀.

~java

/**
* just print "say Hello" string to console
*
* @author rabierre
*/
public class HelloWorld {
    public void sayHello() {
        System.out.println("say Hello");
    }

    public static void main(String[] args) {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.sayHello();
    }
}
Β 
  • jar파일둜 νŒ¨ν‚€μ§•ν•œλ‹€. (.java와 .class만 λ”°λ‘œ νŒ¨ν‚€μ§•ν•˜λŠ” 방법은 μ—¬κΈ°)

    jar cvf helloworld.jar 

~java

/**
* call say HelloWorld class in external jar file package
*
* @author rabierre
*/
public class TestReflection {

    public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
        ClassLoader classLoader = TestReflection .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);

    }
}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:42
Processing time 0.0240 sec