views:

63

answers:

2

Is there a way to pass a class into a property as a Class object?

i.e.

    <managed-property>
        <property-name>clazz</property-name>
        <value>java.lang.Double.class</value>
    </managed-property>
+4  A: 

Yes. But it will be realized as String. You can turn it into Class in your bean, wherever it's needed, using Class.forName(clazz)

You may try using <property-class>java.lang.Class</property-class>, but I'm not sure there is a converter for that built-in

Bozho
Thats not really passing a class in...
DD
@DD I think you are a bit hasty on the downvote button. This works, and not having seen your bean itself, I can't say more.
Bozho
Apologies I should have been more clear in my original post. Will edit to make it more clear.
DD
@DD check my update
Bozho
cant get this to work
DD
how exactly does it fail?
Bozho
+1  A: 

No, there is no way. This is only possible if the class in question has a (default) no-arg constructor. The java.lang.Double doesn't have one. Also, in theory your construct is invalid. The following would have worked if you use a class with a (default) no-arg constructor at the place where java.lang.Double is been definied:

<managed-bean>
    <managed-bean-name>bean</managed-bean-name>
    <managed-bean-class>mypackage.Bean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>clazz</property-name>
        <property-class>java.lang.Class</property-class>
        <value>#{clazz.class}</value>
    </managed-property>
</managed-bean>

<managed-bean>
    <managed-bean-name>clazz</managed-bean-name>
    <managed-bean-class>java.lang.Double</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
</managed-bean>

in combination with

public class Bean {
    private Class<?> clazz; 

    public Class<?> getClazz() {
        return clazz;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }
}

You really need to specify it as a String and make use of Class#forName() to obtain the java.lang.Class from it. Here's a kickoff example:

<managed-bean>
    <managed-bean-name>bean</managed-bean-name>
    <managed-bean-class>mypackage.Bean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>className</property-name>
        <value>java.lang.Double</value>
    </managed-property>
</managed-bean>

in combination with

public class Bean {

    private Class<?> clazz;

    public Class<?> getClazz() {
        return clazz;
    }

    public void setClassName(String name) {
        try {
            this.clazz = Class.forName(name);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("Illegal class name.", e);
        }
    }

}
BalusC