java 用于设置 Class 对象的 Spring 语法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1601015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring syntax for setting a Class object?
提问by Steve B.
Is there a way to set a property in spring to, not an instance of a class, but the class object itself? i.e.
有没有办法在 spring 中设置属性,而不是类的实例,而是类对象本身?IE
Rather than
而不是
<bean>
<property name="prototype" class="a.b.c.Foo">...
giving you an instance of "Foo", something like:
给你一个“Foo”的实例,比如:
<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":
编辑:迄今为止最好的(工作)解决方案 - 使用正常的实例化并在 setter 中派生类。就解决方案而言,我认为我们会将其描述为“作弊”:
<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.
编辑:dtsazza 的方法也有效。
edit: pedromarce's method works as well.
编辑:pedromarce 的方法也有效。
回答by pedromarce
<bean>
<property name="x">
<value type="java.lang.Class">a.b.c.Foo</value>
</property>
</bean>
That should work.
那应该有效。
回答by Andrzej Doyle
You could certainly use the static factory methodClass.forName(), if there's no more elegant syntax (and I don't believe there is):
如果没有更优雅的语法(我不相信有),您当然可以使用静态工厂方法Class.forName():
<property name="x">
<bean class="java.lang.Class" factory-method="forName">
<constructor-arg value="a.b.c.Foo"/>
</bean>
</property>
回答by Kees de Kooter
No. With a bean tag you instruct Spring on how to instantiate a class.
不。通过 bean 标记,您可以指示 Spring 如何实例化一个类。
回答by extraneon
Would <property name="x" class="a.b.c.Foo.class"> work? That should be an instance of a Class object...
<property name="x" class="abcFoo.class"> 会工作吗?那应该是一个 Class 对象的实例......

