通过从注释属性获取的路径实例化对象
1. 有以下注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Trackable {
String builder();
}
2. 此注释的用法:
@Trackable(builder = "pkg1.SomeVO")
public class MyService
3. pkg1.SomeVO
- 是路径Java 对象,应该在我的方面类中进一步实例化。
4. 我得到了 build
的字符串值,它等于来自反射的“pkg1.SomeVO”。
问题是,如何实例化 SomeVO
对象?
我需要这样:MyBuilder mb=new SomeVO()
; 其中MyBuilder
是抽象类,已经定义。
它可能是任何对象,例如 SomeVO2 等,所以我绝对不知道我的方面(参见步骤 3),应该实例化什么类。
1. Have following annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Trackable {
String builder();
}
2. usage of this annotation:
@Trackable(builder = "pkg1.SomeVO")
public class MyService
3. pkg1.SomeVO
- is path to the Java object,that should be instantiated further in my aspect class.
4. I've got String value of build
,that is equals to 'pkg1.SomeVO' from reflection.
The question is,how actually to instantiate SomeVO
object?
I need to it like:MyBuilder mb=new SomeVO()
;
where MyBuilder
is abstract class,already defined.
It may be any object,e. g. SomeVO2 etc.,so I definitely doesn't know in my aspect(see step 3.),what class should be instantiated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
执行类似的操作来获取注释值并创建类。此外,您可能希望在注释中使用默认值字段和
Class
而不是String
以使事情变得更容易。如果您的类没有默认构造函数,您需要弄清楚它需要什么参数:
为了确保您的类属于某种类型(例如
MyBuilder
),您可以将注释设置为:Do something like this to get the annotation value and create the class. Also, you may want to use the default value field and a
Class
instead of aString
in your annotations to make things easier.If your class has no default constructor you need to figure out what args it takes:
To ensure your class is of a certain type (e.g.
MyBuilder
) you can make your annotation be:假设路径是指您的类所在的包(希望位于类路径上)。
如果您的
class
没有默认构造函数,您可以使用getConstructor(Class ...)
(您在哪里传入构造函数的参数类型正在寻找),然后调用newInstance(Object...)
(传入实际值)。类
对象。我建议看一下。Assuming by path, you mean the package your class is in (which is hopefully on the classpath).
If your
class
doesn't have a default constructor, you can find the proper one usinggetConstructor(Class<?> ...)
(where you pass in the types of the arguments of the constructor you are looking for), and then callingnewInstance(Object...)
on that (passing in the actual values).There are a lot of fun methods for use on the
Class
object. I recommend taking a look.