简体   繁体   中英

Method object with generics for return type?

Is there any way to use generics with the Method class in Java? I want to call invoke() on the Method object and have it return the actual return type of the method instead of Object .

You cannot extend Method because, although it is not final , it does not have an accessible constructor.

You can do something like this using composition instead.

public final class MyMethod<T> {

    private final Method method;

    public MyMethod(Method method) {
        this.method = method;
    }

    public T invoke(Object o, Object... args) throws IllegalAccessException, InvocationTargetException {
        return (T) method.invoke(o, args);      // Unchecked cast
    }
}

You can use it like this

MyMethod<Integer> myMethod = new MyMethod<>(BigInteger.class.getMethod("intValue"));
Integer a = myMethod.invoke(new BigInteger("42"));

However, this is not nice (eg the unchecked cast and the checked exceptions).

I suspect this is an XY problem. Some details about what exactly you need this for would make it easier to answer.

正如JB Nizet所说,您不能更改JRE方法,但是可以在执行之前,执行之后或执行前后做一些事情,并且可以更改具有AOP技术的方法(如AspectJ,spring)返回的返回值/对象Google,它将成为您的朋友

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM