Java类信息作为函数参数

import java.lang.reflect.InvocationTargetException;

interface IA{
  void fun();
}

class C implements IA{
  public void fun() {
    System.out.println("fun in C");
  }
}

class D implements IA{
  public void fun() {
    System.out.println("fun in D");
  }
}

class B{
  public void fun(Class<?> ia) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,     NoSuchMethodException, SecurityException {
    System.out.println(ia.getName());
    IA exp=(IA) ia.getDeclaredConstructor().newInstance(); //根据反射机制实例化
    exp.fun(); //多态
  }
}

public class test {
  public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    B myB=new B();
    myB.fun(D.class);
    System.out.println("normal running.");
  }
}

猜你喜欢

转载自www.cnblogs.com/szcloud/p/13168022.html