Andriy Drozdyuk
Andriy Drozdyuk

Reputation: 61061

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 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.

Upvotes: 3

Views: 2714

Answers (4)

Luca Molteni
Luca Molteni

Reputation: 5370

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

Upvotes: 0

ewernli
ewernli

Reputation: 38615

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.

Upvotes: 0

BalusC
BalusC

Reputation: 1108722

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?

Upvotes: 1

stacker
stacker

Reputation: 68962

It's not possible in the way you described.

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

Upvotes: 2

Related Questions