2013-02-04 12 views
3

Reflection을 처음 사용했습니다. 나는 몇 가지 질문과 튜토리얼을 보았다.리플렉션을 사용하여 특정 인터페이스를 구현하는 Java 클래스를 인스턴스화하십시오.

,의 내가 3 개 클래스 A, B에 의해 구현있어 하나의 인터페이스가 있다고 가정 C 보자

public interface MyInterface { 
doJob(); 

}

이제

내가 각 클래스

Class<?> processor = Class.forName("com.foo.A"); 
Object myclass = processor.newInstance(); 

를 호출 할 반사를 사용하여 Object를 만드는 대신 전체 프로세스를 특정 유형으로 제한 할 수는 없습니다. MyInterface 유형 클래스 만 호출하려고합니다.

com.foo.A를 전달하면 클래스 객체를 생성해야하지만 com.foo.B는 B 클래스 객체를 수행해야하지만 com.foo.D가 일부 존재하지만 여전히 MyInterface를 구현하지는 않습니다. shouldn 호출 할 수 없습니다.

내가 어떻게 이것을 달성 할 수 있습니까?

+1

체크 this link ...... http://stackoverflow.com/questions/492184/how-do-you-fi nd-all-of-a-given-class-in-java – sunleo

답변

6

MyInterface newInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { 
    Class<?> cls = Class.forName(className); 
    if (!MyInterface.class.isAssignableFrom(cls)) { 
     throw new IllegalArgumentException(); 
    } 
    return (MyInterface) cls.newInstance(); 
} 
2

음, 자바 반사가 범용 메커니즘하려고, 그래서 당신은 당신이 질문에 제시 한 코드 만 사용하는 경우, 당신은 무엇을 달성하고자 달성 할 수있는 방법은 없습니다. 'MyInterface'를 구현하는 유형 이외의 유형의 생성 객체를 Java에서 어떻게 제한할지 묻는 것과 똑같습니다. Java의 'new'는 일반적인 목적이며 원하는 모든 객체를 만들 수 있습니다.

일반적으로 자신 만의 코드를 작성할 수 있습니다. 그리고 대신에 자신의 코드에 전화를 직접

Class.forName 

호출

당신은 시간을 컴파일/실행 시간에 그런 일을 구현할 수 있습니다. 런타임

public T newInstance(Class<T extends MyInterface cl) { 
    return cl.newInstance(); 
} 

예는 이미

희망이 코드 아래

0

시도를하는 데 도움이 에브 게니 Dorofeev에 의해 게시했습니다 : 컴파일 유형 검사에 대한

예 (당신이 만든 클래스 객체가 필요합니다)

package com.rais.test; 

public class Client { 

    public static void main(String[] args) { 
     try { 
      System.out.println(createObject("com.rais.test.A")); 
      System.out.println(createObject("com.rais.test.D")); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
} 

public static MyInterface createObject(String className) 
     throws ClassNotFoundException, InstantiationException, 
     IllegalAccessException { 

    Class<?> clazz = Class.forName(className); 

    if (MyInterface.class.isAssignableFrom(clazz)) { 
     return (MyInterface) clazz.newInstance(); 

    } else { 

     throw new RuntimeException(
       "Invalid class: class should be child of MyInterface"); 
    } 

} 
관련 문제