tags:

views:

136

answers:

2

How can I create a bean of type Class?

I found a way using getClass() but that requires an instance and cannot be used via factory-method since it is not static. It also requires an extraneous bean be created for this express purpose:

<bean id="foo" class="Foo" />
<bean id="fooClass" factory-bean="foo" factory-method="getClass" />

This isn't so bad if the Foo class is easy to construct, but what if the constructor has required parameters?

I then need to create a Set of Class to wire into another bean via a property. I would create the Set such as:

<util:set id="classSet">
    <ref local="fooClass"/>
</util:set>
+1  A: 

Why would you? Can you provide an example where that's actually needed?

If you only need this as a dependency (e.g. some other bean has a property of type Class), Spring's built-in ClassEditor property editor would convert a regular string into a Class instance with that name for you:

<property name="someClass" value="java.lang.String"/>

The above would result in setSomeClass(Class clazz) setter being called on the bean whose property that is.

ChssPly76
+2  A: 

If you really wanted to do what you describe, then you can do it like this:

<bean id="myClass" class="java.lang.Class" factory-method="forName">
   <constructor-arg value="com.MyClass"/>
</bean>

But as @ChssPly76 said, if you want to inject it into another bean, you only need inject the class name, and Spring will auto-convert it into a class instance for you.

skaffman
I would prefer not to have to create the Class bean at all, but since I need a Set of Class beans and I'm having trouble finding how to use the built-in class editor with util:set. So, I'm thinking this provides the best approach so far.
harschware