Type-safe method reflection in Java

2019-04-30 13:09发布

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

8条回答
唯我独甜
2楼-- · 2019-04-30 13:36

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.

查看更多
Explosion°爆炸
3楼-- · 2019-04-30 13:37

Check out http://jodd.org/doc/methref.html. It uses the Jodd proxy library (Proxetta) to proxy your type. Not sure about its performance characteristics, but it does provide type safety.

An example: Suppose Str.class has method .boo(), and you want to get its name as the string "boo":

Methref<Str> m = Methref.on(Str.class);

// `.to()` returns a proxied instance of `Str` upon which you
// can call `.boo()` Methods on this proxy are empty except when
// you call them, the proxy stores the method's name. So doing this
// gets the proxy to store the name `"boo"`.

m.to().boo();

// You can bget the name of the method you called by using `.ref()`:

m.ref();   // returns "boo"                                 

There's more to the API than the example above: http://jodd.org/api/jodd/methref/Methref.html

查看更多
ら.Afraid
4楼-- · 2019-04-30 13:42

Use Manifold's @Jailbreak for compile-time type-safe access to private fields, methods, etc.

@Jailbreak Foo foo = new Foo();
foo.privateMethod();
foo.privateMethod("hey");
foo._privateField = 88;

 

public class Foo {
  private final int _privateField;

  public Foo(int value) {
    _privateField = value;
  }

  private String privateMethod() {
    return "hi";
  }

  private String privateMethod(String param) {
    return param;
  }
}

Learn more: type-safe-reflection

查看更多
Fickle 薄情
5楼-- · 2019-04-30 13:43

Java misses the syntax sugar to do something as nice as Person.phoneNumber.getter. But if Person is an interface, you could record the getter method using a dynamic proxy. You could record methods on non-final classes as well using CGLib, the same way Mockito does it.

MethodSelector<Person> selector = new MethodSelector<Person>(Person.class);
selector.select().getPhoneNumber();
validateField(data, selector.getMethod(), options);

Code for MethodSelector: https://gist.github.com/stijnvanbael/5965609

查看更多
Lonely孤独者°
6楼-- · 2019-04-30 13:48

There isn't anything in the language yet - but part of the closures proposal for Java 7 includes method literals, I believe.

I don't have any suggestions beyond that, I'm afraid.

查看更多
何必那么认真
7楼-- · 2019-04-30 13:51

The framework picklock lets you do the following:

class Data {
  private PhoneNumber phoneNumber;
}

interface OpenData {
  PhoneNumber getPhoneNumber(); //is mapped to the field phoneNumber
}

Object data = new Data();
PhoneNumber number = ObjectAccess
  .unlock(data)
  .features(OpenData.class)
  .getPhoneNumber();

This works in a similar way setters and private methods. Of course, this is only a wrapper for reflection, but the exception does not occur at unlocking time not at call time. If you need it at build time, you could write a unit test with:

 assertThat(Data.class, providesFeaturesOf(OpenData.class));
查看更多
登录 后发表回答