Can a Java class add a method to itself at runtime

2020-01-23 04:15发布

Can a class add a method to itself at runtime (like from a static block), so that if someone is performing reflection on this class, they'll see the new method, even though it wasn't defined at compile time?

Background:

A framework I'm using expects Action classes to be defined that have a doAction(...) method, by convention. The framework inspects these classes at runtime to see what type of parameters are available in their doAction() method. For example: doAction(String a, Integer b)

I'd like each class to be able to programatically generate its doAction() method with various parameters, just-in-time when it is inspected. The body of the method can be empty.

10条回答
相关推荐>>
2楼-- · 2020-01-23 04:30

I'm not sure that is possible. However, you could use AspectJ, ASM, etc. and weave these methods into the appropriate classes.

The other alternative is to use composition to wrap the target class and provide the doAction method. You would end up delegating to the target class in this case.

查看更多
爷的心禁止访问
3楼-- · 2020-01-23 04:31

No, that is not (easily) possible in Java.

It sounds like you are trying to use Java as if it is a dynamic programming language. For example, Ruby has open classes: you can add and remove methods from Ruby classes at runtime. In Ruby, you can also have a "method missing" method in your class, that will be called when you try to call a method that doesn't exist in the class. Such a thing also doesn't exist in Java.

There is a version of Ruby that runs on the JVM, JRuby, and it has to do very difficult tricks to make open classes work on the JVM.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-01-23 04:34

I've never tried anything quite like that myself, but you should have a look at ASM, cglib, and Javassist.

查看更多
做自己的国王
5楼-- · 2020-01-23 04:38

You can have a doAction method which does whatever you would like the generated method to do. Is there a reason it needs to be generated or can it be dynamic?

查看更多
登录 后发表回答