Java获取编译时安全方法名称 [英] Java get compile-time safe method name

查看:133
本文介绍了Java获取编译时安全方法名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用反射类和注释时,我发现没有明确的方法以编译时安全的方式引用方法名称。我真正想要的是能够引用注释中的方法。可能类似于:

  @CallAfter(method = Foo.class.foo())
void Bar() {...}

目前你只能用字符串做这个,这不是编译时间安全..这是一个问题,因为它破坏了静态类型的Java。我找到的唯一解决方案就是下面的内容。但是,这仍然无法帮助引用注释中的方法。 :(

  public static String methodName = null; 

public static void main(String [] args ){

// .foo()是编译时安全的
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();
返回null;
});
}

公共接口IFoo {
Object foo();
}

有没有人对此有任何想法,意见或解决方案?

解决方案

我写了<$ c可以提供编译安全方法引用的$ c> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆