2012-01-15 51 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()代替。

相关问题