动态生成专业化类别
给定抽象父类动态生成专业化类的最佳方法是什么?
例如,假设这是我的父类:
public abstract class Parent {
public Parent(int i) {
// initialization here ...
}
@AnImportantAnnotation("")
public abstract Object testMethod();
}
那么我想要一个接收抽象类并返回它的实例的方法,例如:
public class Manager {
public static <T> T getInstance(Class<T> c) {
return <"instance of dynamically generated specialization class">;
}
public static void main(String[] args) {
Parent parent = getInstance(Parent.class);
}
}
getInstance
方法,重写在 Parent
类中找到的抽象方法。这些生成方法的代码取决于其相应父方法的注释。
此外,生成的类应该定义与其父类相同的构造函数。例如,生成的类应该相当于:
public class Son extends Parent {
//generated constructor
public Son(int i) {
super(i);
}
public Object testMethod() {
// dynamically generated behaviour guided by annotations on the overridden method
return aReturnValue;
}
}
我更喜欢仅从内存中执行此操作的指针(不将文件读/写到磁盘),并且如果可能的话,不使用外部库(例如,Javassist)。然而,对依赖于此类库的技术的解释也受到高度赞赏。 非常感谢您的帮助。
What is the best way to dynamically generate a specialization class given an abstract parent class ?
For example, let's say this is my parent class:
public abstract class Parent {
public Parent(int i) {
// initialization here ...
}
@AnImportantAnnotation("")
public abstract Object testMethod();
}
Then I would like to have a method that receives an abstract class and returns and instance of it, like for example:
public class Manager {
public static <T> T getInstance(Class<T> c) {
return <"instance of dynamically generated specialization class">;
}
public static void main(String[] args) {
Parent parent = getInstance(Parent.class);
}
}
The class of the instance returned by the getInstance
method, overrides the abstract methods found in the Parent
class. The code of these generated methods depends on the annotations of their corresponding parent methods.
In addition, the generated class should define the same constructors than its parent. For example, the generated class should be equivalent to:
public class Son extends Parent {
//generated constructor
public Son(int i) {
super(i);
}
public Object testMethod() {
// dynamically generated behaviour guided by annotations on the overridden method
return aReturnValue;
}
}
I would prefer pointers to how to do this only from memory (no read/write of files to disk) and if possible without using external libraries (e.g., Javassist). However, explanations of techniques depending on such libraries are also -highly- appreciated.
Thanks a lot for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于类,我认为没有 Javassist 这样的库是不可能的,但是,如果您可以使用接口而不是抽象类,则可以使用 java.lang.reflect.Proxy。
With classes, I don't think it is possible without a library such as Javassist, however, if you can use interfaces instead of abstract classes, you can use java.lang.reflect.Proxy.