开发者

Class parameter in Faces Config

开发者 https://www.devze.com 2022-12-23 22:00 出处:网络
Is there a way to pass a class into a property as a Class ob开发者_JAVA百科ject? i.e. <managed-property>

Is there a way to pass a class into a property as a Class ob开发者_JAVA百科ject?

i.e.

    <managed-property>
        <property-name>clazz</property-name>
        <value>java.lang.Double.class</value>
    </managed-property>


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


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);
        }
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消