从 Java 类型创建实例
我想知道是否可以从 Java 类型创建实例并填充参数化列表?
我有一个带有成员变量 List
(以及一些原始类型)UserDefinedType
。 list
在 UserDefinedType
上使用反射(处理自定义注释)我只处理具有特定注释的成员变量。如果在注释上设置了特定属性,则意味着它是AnotherUserDefinedType,而不是原始类型,因此处理方式有所不同。在这种情况下,我要做的正是我对 UserDefinedType 所做的事情。
需要注意的是,我必须从 Field.getGenericType()
创建 AnotherUserDefinedType
的实例,并以某种方式将它们添加到 List
的参数化类型中。 code> 并调用 UserDefinedType.setAnotherUserDefinedType(List
我试图找到一些有关它的信息,但现在不知所措。任何帮助将不胜感激。
I was wondering if its possible to create an instance from a Java Type and populate a parameterised list?
I've got a Type UserDefinedType
with a member variable List<AnotherUserDefinedType> list
(as well as some primitive types)
Using reflection (to process custom annotations) on UserDefinedType
I am processing only member variables with a specific annotation. If a particular property is set on the annotation it means that it is AnotherUserDefinedType
as opposed to a primitive type so it is handled differently. In this case I was to do exactly what I did with UserDefinedType
.
The caveat is I have to create an instance of AnotherUserDefinedType
from Field.getGenericType()
, and somehow add them to a parameterised type of List<AnotherUserDefinedType>
and call UserDefinedType.setAnotherUserDefinedType(List<AnotherUserDefinedType> list)
.
I've tried to find some information on it, but am at a loss now. Any assistance would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果参数类型本身不是类型参数,并且是一个具有默认无参构造函数的类,则可以执行以下操作:
尽管这很糟糕,并且在这种情况下不会完成任何您无法完成的事情无需反射(通过直接实例化
AnotherUserDefinedType
)。也许您可以通过这一切来扩展您的核心目标?也许我们可以建议一种更清洁的方法。如果列表本身是用类类型参数参数化的:
那么这是不可能的。由于类型擦除,该类型在运行时不可用。
所以基本上只有当类型是静态已知的时候才有可能,并且如果类型是静态已知的,您可能不需要反射。
If the parameter type isn't itself a type parameter, and is a class with a default no-argument constructor, you can do something like this:
It's pretty gross though, and in this case doesn't accomplish anything you couldn't do without reflection (by instantiating
AnotherUserDefinedType
directly). Maybe you can expand on what your core goal is through all this? Perhaps there's a cleaner approach that we could suggest.If the list is itself parameterized with a class type parameter:
then this is impossible. The type will not be available at runtime due to type erasure.
So basically it's only possible when the type is statically known, and if the type is statically known you probably don't need reflection.