2019-03-22——Java反射 Method

Method类描述的是一个方法的信息

常用方法说明

方法 说明
getDefaultValue() 返会该注解方法对象表示的成员默认值,如果成员属于基本数据类型,则返回对应的包装类实例;如果没有默认值或者该方法实例不表示注解方法,则返回null
getGenericReturnType() 返回一个Type对象,该Type对象表示该方法对象的返回类型,会保留泛型
getReturnType() 返回一个Class对象,该Class对象表示该方法对象的返回对象,会擦除泛型
isBridge() 判断该方法对象是否桥接方法,如果是则返回true,否则为false
isDefault() 判断该方法对象是否为默认方法,如果是则返回true,否则为false
invoke(Object obj, Object... args) 对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。

bridge方法

public interface IBridge<T> {
    T getValue(T t);
}


public class BridgeMethod implements IBridge<String>{
    @Override
    public String getValue(String s) {
        System.out.println("this is getValue(String s)");
        return s;
    }
}
    static void t1(){
        Method[] methods = BridgeMethod.class.getDeclaredMethods();
        Arrays.stream(methods).forEach(method -> {
            if("getValue".equalsIgnoreCase(method.getName())){
                System.out.println(method.toGenericString());
                System.out.println(method.isBridge());
                System.out.println(method.isSynthetic());
            }
        });
    }


    static void t2() throws Exception {
        Method method = BridgeMethod.class.getMethod("getValue", Object.class);
        System.out.println(method.toGenericString());
        method.invoke(new BridgeMethod(),"wyw");
    }

t1方法执行的结果是

public java.lang.String practice.t3.BridgeMethod.getValue(java.lang.String)
false
false
public java.lang.Object practice.t3.BridgeMethod.getValue(java.lang.Object)
true
true

t2方法执行的结果是

public java.lang.Object practice.t3.BridgeMethod.getValue(java.lang.Object)
this is getValue(String s)

由t2方法的结果可以看出,虽然获取到的是编译器生成的bridge方法,但是实际执行的还是BridgeMethod类中实际定义的方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容