2012-01-15 93 views
-2

我有一個類型爲FooProcess(接口)[空對象]的對象'Foo Action'。 我想初始化'Foo Action'作爲FooProcess的一個子類的對象[FooOneFooTwo]。如何使用Spring Framework從類路徑/名稱創建對象?

使用Spring Framework,我能夠創造ArrayListFooList(中FooProcess子類的名稱列表),現在我想初始化FooAction的一個子類。 (給定參數selected定義,我希望它作爲初始化哪個類)

FooProcess所有子類都具有接受String構造。

我的問題特別是在這條線

FooAction = component.getClass().getConstructor(f); 

完整的方法:

public FooProcess Load(String selected, String f) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException{ 
    ArrayList<String> FooList = new ArrayList<String>(); 
    final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true); 
    provider.addIncludeFilter(new AssignableTypeFilter(FooProcess.class)); 
    for (BeanDefinition component : provider.findCandidateComponents("org.project.foomodule.systems")) { 
     if(selected == component.getBeanClassName()){ 
     FooAction = component.getClass().getConstructor(f); 
    } } 
    return FooAction; 
} 
+0

這是什麼問題? – skaffman 2012-01-15 12:56:57

+0

爲什麼不使用Spring Bean Factory來實例化對象並注入依賴關係? – duffymo 2012-01-15 12:58:30

+0

@skaffman我在帖子中暗示的'問題'並不能滿足我需要,而且IDE說它在語法上是錯誤的。 – JD009 2012-01-15 12:58:56

回答

0

看看這個,它的工作原理相同

import java.awt.Rectangle; 
import java.lang.reflect.Constructor; 
import java.lang.reflect.InvocationTargetException; 

public class SampleInstance { 

    public static void main(String[] args) { 

     Rectangle rectangle; 
     Class rectangleDefinition; 
     Class[] intArgsClass = new Class[] { int.class, int.class }; 
     Integer height = new Integer(12); 
     Integer width = new Integer(34); 
     Object[] intArgs = new Object[] { height, width }; 
     Constructor intArgsConstructor; 

     try { 
      rectangleDefinition = Class.forName("java.awt.Rectangle"); 
      intArgsConstructor = rectangleDefinition 
        .getConstructor(intArgsClass); 
      rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); 
     } catch (ClassNotFoundException e) { 
      System.out.println(e); 
     } catch (NoSuchMethodException e) { 
      System.out.println(e); 
     } 
    } 

    public static Object createObject(Constructor constructor, 
      Object[] arguments) { 

     System.out.println("Constructor: " + constructor.toString()); 
     Object object = null; 

     try { 
      object = constructor.newInstance(arguments); 
      System.out.println("Object: " + object.toString()); 
      return object; 
     } catch (InstantiationException e) { 
      System.out.println(e); 
     } catch (IllegalAccessException e) { 
      System.out.println(e); 
     } catch (IllegalArgumentException e) { 
      System.out.println(e); 
     } catch (InvocationTargetException e) { 
      System.out.println(e); 
     } 
     return object; 
    } 
} 
0

一個問題,我看到:你」重新調用BeanDefinition上的getClass(),它將成爲BeanDefinition類本身,而不是定義的Bean的類。

另外,您不應該在Java中將字符串與==相比較。使用.equals()代替。