Steve B.
Steve B.

Reputation: 57294

Spring syntax for setting a Class object?

Is there a way to set a property in spring to, not an instance of a class, but the class object itself? i.e.

Rather than

<bean>
   <property name="prototype" class="a.b.c.Foo">...

giving you an instance of "Foo", something like:

<bean>
  <property name="prototype" class="java.lang.Class" value="a.b.c.Foo.class"...

edit: best (working) solution so far - use the normal instantiation and derive the class in the setter. In terms of solutions I think this we'd describe this as "cheating":

<bean class="Bar">
   <property name="prototype" class="a.b.c.Foo">...


public class Bar{
        public void setPrototype(Object o){
                this.prototypeClass=o.getClass();

edit: dtsazza's method works as well.

edit: pedromarce's method works as well.

Upvotes: 31

Views: 20867

Answers (4)

pedromarce
pedromarce

Reputation: 5669

<bean>
   <property name="x">
      <value type="java.lang.Class">a.b.c.Foo</value>
   </property>
 </bean>

That should work.

Upvotes: 40

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

You could certainly use the static factory method Class.forName(), if there's no more elegant syntax (and I don't believe there is):

<property name="x">
   <bean class="java.lang.Class" factory-method="forName">
      <constructor-arg value="a.b.c.Foo"/>
   </bean>
</property>

Upvotes: 11

extraneon
extraneon

Reputation: 23950

Would <property name="x" class="a.b.c.Foo.class"> work? That should be an instance of a Class object...

Upvotes: 0

Kees de Kooter
Kees de Kooter

Reputation: 7195

No. With a bean tag you instruct Spring on how to instantiate a class.

Upvotes: 0

Related Questions