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.0056 sec