开发者

Create Java method from a string?

Is it possible in Java, to declare a method with a string instead of an identifier?

For example can I do开发者_如何学Go something like the following:

class Car{

     new Method("getFoo", {
          return 1+1;
     });
}

//Use it
Car car = new Car();
car.getFoo();

EDIT: I am adding a Purpose WHY I need this. In order to not hardcode method names when using Jersey and its UriBuilder, which requires a method name: https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/core/UriBuilder.html

See path() method with signature:

 public abstract UriBuilder path(java.lang.Class resource,
                            java.lang.String method)
                     throws java.lang.IllegalArgumentException

So then I may just use string constants and not worry that the method name will ever be different from the string that I am passing to the path() method.

I hope my question is clear, if not - let me know and I can clarify it.


It's not possible in the way you described.

The closest thing is probably the asm library to create java bytecode.


As per the purpose, why don't you just have a single method and let it act/behave differently depending on the caller and the parameters?


It's indeed not great to have the method name as string in the code, but if feel the usage of reflection from your side and from jax-rs side should compensate so that this does not happen.

Let me clarify. I guess you are using UriBuilder because you want to expose a service, or something similar. If you reflect on the class and list the method, then pass their name in UriBuilder, which also reflect on the class, the method is never explicitly mentioned in the source.

I'm not familiar with jax-rs though, and without knowing more about what you exactly try to achieve (your edit does provide a bit more information, but does not explain the end goal you have in mind), I don't know if that makes sense. But it could be a track to follow.


If you can consider using another language on the JVM, Groovy can do that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜