Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Java/reflection: Difference between revisions

From ZeroWiki
imported>rabierre
No edit summary
(Repair batch-0008 pages from live compare)
 
(11 intermediate revisions by one other user not shown)
Line 1: Line 1:
= 설명 =
= 설명 =
* 현재 프로젝트내의 class가 아닌 외부 패키지 class의 method를 호출하는 방법.  
* classpath를 이용해 현재 프로젝트내의 class가 아닌 외부 패키지 class의 method를 호출하는 방법.  
* 외부 프로젝트는 jar로 패키징 한다.  
* 외부 프로젝트는 jar로 패키징 한다.  
* jar파일에 존재하는 class를 현재 프로젝트에서 동적으로 호출할 수 있다.
* jar파일에 존재하는 class를 현재 프로젝트에서 동적으로 호출할 수 있다.
Line 6: Line 6:
** ORM(Object-Relational-MApping)이 아닌 방식으로 DAO를 만들 때 사용되기도 한다.
** ORM(Object-Relational-MApping)이 아닌 방식으로 DAO를 만들 때 사용되기도 한다.
= 코드 =
= 코드 =
* 문자열을 출력하는 샘플 클래스.
  ~java
  ~java
   
   
  /**
  /**
  * just print "say Hello" string to console
  * just print "say Hello" string to console
*
* @author rabierre
  */
  */
  public class HelloWorld {
  public class HelloWorld {
Line 16: Line 19:
     }
     }
   
   
     public static void main(String[] args) {
     public static void main(String[] args) {
         HelloWorld helloWorld = new HelloWorld();
         HelloWorld helloWorld = new HelloWorld();
         helloWorld.sayHello();
         helloWorld.sayHello();
     }
     }
  }
  }
 
* jar파일로 패키징한다. (.java와 .class만 따로 패키징하는 방법은 [http://kldp.org/node/75924 여기])
    jar cvf helloworld.jar
  ~java
  ~java
   
   
  /**
  /**
  * call say HelloWorld class in external jar file package
  * call say HelloWorld class in external jar file package
*
* @author rabierre
  */
  */
  public class TestReflection {
  public class TestReflection {
   
   
     public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
     public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
         ClassLoader classLoader = Test.class.getClassLoader();
         ClassLoader classLoader = TestReflection .class.getClassLoader();
         System.out.println(classLoader.getClass().getName());
         System.out.println(classLoader.getClass().getName());
   
   
         URLClassLoader urlClassLoader = new URLClassLoader(
         URLClassLoader urlClassLoader = new URLClassLoader(
             new URL[]{
             new URL[]{
                 new URL("file:/Users/fharenheit/Projects/openflamingo/helloworld.jar")
                 new URL("file:/Users/fharenheit/Projects/openflamingo/helloworld.jar")
             }, classLoader
             }, classLoader
Line 44: Line 53:
         Object object = helloWorld.newInstance();
         Object object = helloWorld.newInstance();
   
   
         Method[] declaredMethods = helloWorld.getDeclaredMethods();
         Method[] declaredMethods = helloWorld.getDeclaredMethods();
         for (int i = 0; i < declaredMethods.length; i++) {
         for (int i = 0; i < declaredMethods.length; i++) {
             Method declaredMethod = declaredMethods[i];
             Method declaredMethod = declaredMethods[i];
             System.out.println(declaredMethod.getName());
             System.out.println(declaredMethod.getName());
         }
         }
Line 55: Line 64:
     }
     }
  }
  }

Latest revision as of 01:40, 27 March 2026

설명

  • 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);

    }
}