简体   繁体   中英

How to access method properties at compile-time?

I would like to access the usual reflection properties of a specific method without relying on String s.

Is there any way to get from the method- Identifier to its reflection properties, like parameter types?

void run() {
    java.lang.reflect.Method m = myMethod.getMethod(); // how? 
    Class<?>[] argClasses = m.getParameterTypes();
}

int myMethod(String arg) {
   // ...
}

The piece myMethod.getMethod() is not valid. It is my way of saying "get from the method-identifier to the java.lang.reflect.Method object".

The string-way I do not want to use would be similar to m = getClass().getDeclaredMethod("myMethod", ...)

I use myMethod like a regular identifier and not as a String, ie "myMethod" . I think this would be beneficial for refactoring, where someone renames myMethod to hisMethod -- the relation via the String -name would break, where the relation via the identifier would be refactored as well.

In java methods aren't first class citizens, so there is no solutions in Java for this problem.

Yet I had a similar problem and forged a small tool named picklock for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM