泛型擦除留下的方法

接口

public interface SuperClass<T> {
    void method(T t);
}

实现类

public class ChildClass implements SuperClass<String> {
    @Override
    public void method(String s) {
    System.out.println(s);
  } 
}

泛型是在jdk1.5引入的,为了向前兼容,所以会在编译时去掉泛型(泛型擦除)。SuperClass接口中的method方法的参数在虚拟机中只能是Object。

接口(泛型擦除后)

public interface SuperClass {
    void method(Object  t);
}

实现类(javap -p ChildClass.class 查看编译后的ChildClass )

public class ChildClass implements SuperClass<java.lang.String> {
  public ChildClass();
  public void method(java.lang.String);
  public void method(java.lang.Object);
}

反射调用

 public static void main(String[] args) throws Exception {
        ChildClass obj = new ChildClass ();
        Method method = ChildClass.class.getMethod("method", Object.class);
        System.out.println(method.isBridge()); // true
    }

相关文章:

  • 2022-01-06
  • 2021-12-10
  • 2021-12-10
  • 2022-02-04
  • 2021-06-03
  • 2022-12-23
  • 2022-12-23
  • 2022-02-22
猜你喜欢
  • 2022-01-03
  • 2021-11-12
  • 2022-12-23
  • 2021-12-10
  • 2022-12-23
  • 2021-12-10
  • 2021-07-27
相关资源
相似解决方案