Create Java method from 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 target WHY I need it. In order not to use the method names of the method when using Jersey and its UriBuilder, for which the method name is required: 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, I can just use string constants and not worry that the method name will never be different from the string that I pass to the path () method.

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

+3
source share
4 answers

, .

- , , asm - Java.

+2

, / - ?

+1

, , jax-rs , .

. , UriBuilder, - . , UriBuilder, , .

I am not familiar with jax-rs, although without knowing more about what you are exactly trying to achieve (your editing gives a little more information, but does not explain the final goal that you have in mind), I don’t know I don’t know if it has the meaning. But it could be a trace.

0
source

If you can use a different language in the JVM, Groovy can do it.

0
source

Source: https://habr.com/ru/post/1749607/


All Articles