java安全策略 禁止反射,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) { ... }

In order to call it, I would have to do:

validateField(data, "phoneNumber", options);

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

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) { ... }

And call it with:

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..

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.

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);

}

}

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值