简体   繁体   English

如何在编译时访问方法属性?

[英]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. 我想访问特定方法的通常反射属性,而不依赖String

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. 片段myMethod.getMethod()无效。 It is my way of saying "get from the method-identifier to the java.lang.reflect.Method object". 这是我说“从方法标识符获取到java.lang.reflect.Method对象”的方式。

The string-way I do not want to use would be similar to m = getClass().getDeclaredMethod("myMethod", ...) 我不想使用的字符串方式类似于m = getClass().getDeclaredMethod("myMethod", ...)

I use myMethod like a regular identifier and not as a String, ie "myMethod" . 我将myMethod用作常规标识符,而不是字符串,即"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. 我认为这对于重构很有用,因为有人将myMethod重命名为hisMethod -通过String -name的关系将中断,通过标识符的关系也将被重构。

In java methods aren't first class citizens, so there is no solutions in Java for this problem. 在Java中,方法不是一等公民,因此Java中没有针对此问题的解决方案。

Yet I had a similar problem and forged a small tool named picklock for this purpose. 但是我遇到了类似的问题,为此目的锻造了一个名为picklock的小工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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