Java获取编译时安全方法名称 [英] Java get compile-time safe method name
问题描述
在使用反射类和注释时,我发现没有明确的方法以编译时安全的方式引用方法名称.我真正想要的是能够在注释中引用一个方法.可能看起来像:
@CallAfter(method=Foo.class.foo())void Bar() { ... }
目前你只能用字符串来做这件事,这在编译时是不安全的.这是一个问题,因为它破坏了 Java 的静态类型.我找到的唯一解决方案类似于下面的内容.然而,这仍然无助于在注释中引用方法.:(
public static String methodName = null;公共静态无效主(字符串 [] args){//.foo() 是编译时安全的loadMethodName(IFoo.class).foo();System.out.println(methodName);}公共静态<T>T loadMethodName(Class mock) {返回 (T) Proxy.newProxyInstance(mock.getClassLoader(), new Class[] { mock },(对象,方法,参数)->{methodName = method.getName();返回空;});}公共接口 IFoo {对象 foo();}
有没有人对此有任何想法、意见或解决方案?
我编写了一个 AnnotationProcessor
可以提供编译安全的方法引用.
While working with the reflection class and annotations I have found that there is no clear way to reference a method name in a compile-time safe way. What I really want is to be able to reference a method within an annotation. Might look something like:
@CallAfter(method=Foo.class.foo())
void Bar() { ... }
At the moment you can only do this with strings, which is not compile time safe.. This is a problem because it undermines Java being statically typed. The only solution I have found is something like what is below. However this still does not help with referencing a method in an annotation. :(
public static String methodName = null;
public static void main(String[] args) {
// .foo() is compile-time safe
loadMethodName(IFoo.class).foo();
System.out.println(methodName);
}
public static <T> T loadMethodName(Class<T> mock) {
return (T) Proxy.newProxyInstance(mock.getClassLoader(), new Class[] { mock },
(obj, method, args) -> {
methodName = method.getName();
return null;
});
}
public interface IFoo {
Object foo();
}
Does anyone have any thoughts, comments, or a solution to this?
I write an AnnotationProcessor
that can provide a compile-safe method reference. See it on github
It will give a compile error if the referenced method not exists.
And it works in eclipse, see the snapshot.
这篇关于Java获取编译时安全方法名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!