Java中的类型安全方法反射 [英] Type-safe method reflection in Java

查看:114
本文介绍了Java中的类型安全方法反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以一种类型安全的方式在类上引用方法的方法是否可行?一个基本示例是,如果我想创建类似以下实用程序的函数:

Is any practical way to reference a method on a class in a type-safe manner? A basic example is if I wanted to create something like the following utility function:

public Result validateField(Object data, String fieldName, 
                            ValidationOptions options) { ... }

为了进行调用,要做:

validateField(data, "phoneNumber", options);

这迫使我要么使用魔术字符串,要么使用该字符串声明常量。

Which forces me to either use a magic string, or declare a constant somewhere with that string.

我很确定没有办法用Java语言解决这个问题,但是是否有某种(生产级)预编译器或替代编译器可以提供工作吗? (类似于AspectJ扩展Java语言的方式)最好改为执行以下操作:

I'm pretty sure there's no way to get around that with the stock Java language, but is there some kind of (production grade) pre-compiler or alternative compiler that may offer a work around? (similar to how AspectJ extends the Java language) It would be nice to do something like the following instead:

public Result validateField(Object data, Method method, 
                            ValidationOptions options) { ... }

并调用它

validateField(data, Person.phoneNumber.getter, options);


推荐答案

就像其他人提到的那样,没有真正的方法这个...我还没有看到支持它的预编译器。至少可以这样说,语法会很有趣。即使在您的示例中,它也只能覆盖用户可能希望执行的一小部分潜在的反射可能性,因为它将无法处理带有参数的非标准访问器或方法等。

As others mention, there is no real way to do this... and I've not seen a precompiler that supports it. The syntax would be interesting, to say the least. Even in your example, it could only cover a small subset of the potential reflective possibilities that a user might want to do since it won't handle non-standard accessors or methods that take arguments, etc..

即使无法在编译时检查,如果您希望不良代码尽快失败,那么一种方法是在类初始化时解析引用的Method对象。

Even if it's impossible to check at compile time, if you want bad code to fail as soon as possible then one approach is to resolve referenced Method objects at class initialization time.

假设您有一个实用方法来查找可能引发错误或运行时异常的Method对象:

Imagine you have a utility method for looking up Method objects that maybe throws error or runtime exception:

public static Method lookupMethod( Class c, String name, Class... args ) {
    // do the lookup or throw an unchecked exception of some kind with a really
    // good error message
}

然后在您的类中,使用常量预先解析将要使用的方法:

Then in your classes, have constants to preresolve the methods you will use:

public class MyClass {
    private static final Method GET_PHONE_NUM = MyUtils.lookupMethod( PhoneNumber.class, "getPhoneNumber" );

    ....

    public void someMethod() {
        validateField(data, GET_PHONE_NUM, options);
    }
}

至少在MyClass为

At least then it will fail as soon as MyClass is loaded the first time.

我经常使用反射,尤其是bean属性反射,并且我已经习惯于在运行时后期处理异常。但是,由于种种其他原因,这种风格的Bean代码往往会出错,而且非常动态。对于介于两者之间的内容,上述方法会有所帮助。

I use reflection a lot, especially bean property reflection and I've just gotten used to late exceptions at runtime. But that style of bean code tends to error late for all kinds of other reasons, being very dynamic and all. For something in between, the above would help.

这篇关于Java中的类型安全方法反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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