java反射案例:

新建学生:

public class Student {
   public void show(){
      System.out.println("is show()");
   }
}

创建pro.txt文件:

className = com.lmj.javahomework.Student
methodName = show

创建演示测试类:

public class Demo{
      public static void main(String[] args) throws Exception {
               Class student=Class.forName(getValue("className"));
               Method m=student.getMethod(getValue("methodName"));
               m.invoke(student.getConstructor().newInstance());
   }
       //此方法接收一个key,在配置文件中获取相应的value
   public static String getValue(String key) throws IOException {
      Properties pro = new Properties();//获取配置文件的对象
      FileReader in = new FileReader("src/com/lmj/javahomework/pro.txt");//获取输入流
      pro.load(in);//将流加载到配置文件对象中
      in.close();
      return pro.getProperty(key);//返回根据key获取的value值
   }
}

运行演示,控制台打印是show()

Class类是jdk中的以静态生成的类,动态生成类是以静态类作为模板填充的。 

猜你喜欢

转载自blog.csdn.net/qq_41063141/article/details/83216322