(Java) 为通过反射创建的新对象创建方法?
我的类中有抽象方法,需要由使用我的项目的单独项目中的外部类来实现。
-- 所有类instanceof A最初都是使用反射生成的--
所以无论如何,假设类A是抽象的,类B(非抽象)扩展了A
B具有类A中所有未实现的方法,因为B在我的工作空间中,所以我知道添加这些方法。
C 也扩展了 A,但 C 仅具有 A 中抽象方法的子集。然而,C 并不在我的工作区中。
因此,对于 C 中而不是 A 中的每个抽象方法,我需要找到某种方法来添加 A 的方法,如下所示:(
对于每个方法)
public <corresponding return type> <missingMethodName>() { return null; }
这可能吗?
PS 请假设我要么必须完全重写我的代码才能与我无法控制的对象同步,要么实现像我上面提到的那样的解决方案。
I have abstract methods in a class that need to be implemented by a foreign class in a SEPARATE project that uses my project.
-- All classes instanceof A are initially generated using reflection --
So anyway, say Class A is abstract, and Class B (non-abstract) extends A
B has all the unimplemented methods in Class A because B is in my workspace so I know to add those methods.
C also extends A, but C only has a subset of the abstract methods in A. C, however, is not in my workspace.
Therefore, for each abstract method in C NOT in A, I need to find some way to add the method for A like so:
(For each method)
public <corresponding return type> <missingMethodName>() { return null; }
Is this possible?
P.S. Please assume that I either have to completely rewrite my code to be in sync with the objects I have no control over, or implement a solution like the one I am alluding to above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,除非我没理解你的意思,否则你的要求并没有多大意义。
如果你想将一个方法注入
到 C 中,而 C 扩展了 A,而 A 没有实现该方法,那么它到底会做什么?
如果你想在A中提供默认实现,那很好,并且不会影响C。如果你在A中添加抽象方法,C必须实现它们,将自己标记为抽象,否则它不会编译(或抛出序列化,或者一些奇怪的错误)如果你使用用旧的 A 编译的 C 运行。
No, unless I'm reading you incorrectly, what you're asking for doesn't really make much sense.
If you wanted to inject a method
into C, which extends A, which doesn't implement that method, what would it exactly do?
If you want to provide a default implementation in A, that's fine, and it won't affect C. If you add abstract methods into A, C must implement them, mark itself as abstract, or it won't compile (or throw serialization, or some weird error) if you run with a C compiled with an older A.
您永远不需要这样做,因为可以在子类实例上调用任何具有 super 实现的实例方法。
您可以使用字节代码添加这些方法,但它们唯一的区别是更改 getDefinedMethods() 的列表。但是,它不会改变类对象的行为。
You should never need to do this as any instance method which has a
super
implementation can be called on a sub-class instance.You can add these methods using byte code, but the only difference they would make is to change the list of getDefinedMethods(). However it wouldn't change the behaviour of the objects of the class.
这很困难,但你可以使用 Javassist 来完成
its quiet difficult but you can do it with Javassist