开发者

(Java) Creating methods for new object created via reflection?

开发者 https://www.devze.com 2023-04-11 04:57 出处:网络
I have abstract methods in a class that need to be implemented by a foreign class in a SEPARATE project that uses my project.

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.

开发者_JAVA技巧

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.


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

public <corresponding return type> <missingMethodName>() { super.<missingMethodName>(); }

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.


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.


its quiet difficult but you can do it with Javassist

Javassist (Java programming assistant) is a Java library providing a means to manipulate the Java bytecode of an application.1 In this sense Javassist provides the support for structural reflection, i.e. the ability to change the implementation of a class at run time. Bytecode manipulation is performed at load-time through a provided class loader. http://en.wikipedia.org/wiki/Javassist

0

精彩评论

暂无评论...
验证码 换一张
取 消