反射-Class对象功能-获取Constructor
Student类
public class Student { public void sleep(){ System.out.println("sleep..."); } }
配置文件
#在src下创建的pro.properties文件 #类名 className=cn.itcast.domain.Student #类中的方法名 methodName=sleep
ReflectTest类测试
public class ReflectTest { /* 前提:不能改变该类的任何代码,可以创建任意类的对象,可以执行任意方法 */ public static void main(String[] args) throws Exception { //加载配置文件 //1.1创建Properties对象 Properties pro = new Properties(); //1.2加载配置文件,转换为一个集合 //1.2.1获取class目录下的配置文件 ClassLoader classLoader = ReflectTest.class.getClassLoader(); InputStream is = classLoader.getResourceAsStream("pro.properties"); pro.load(is); //2.获取配置文件中定义的数据 String className = pro.getProperty("className"); String methodName = pro.getProperty("methodName"); //3.加载该类进内存 Class cla = Class.forName(className); //4.创建对象 Object o = cla.newInstance(); //5.获取方法对象 Method method = cla.getMethod(methodName); //6.执行方法 method.invoke(o); }
想运行其他类中的方法时,就直接可以去pro.properties配置文件中修改成你想运行的类名和方法名即可
反射-Class对象功能-获取Method
获取class对象的方式:
public static void main(String[] args) throws Exception { //1.Class.forName("全类名") Class aClass = Class.forName("cn.itcast.domain.Person"); System.out.println(aClass); //2.类名.class Class personClass = Person.class; System.out.println(personClass); //3.对象.getClass Person person = new Person(); Class aClass1 = person.getClass(); System.out.println(aClass1); }
Person类
public class Person { private String name; private int age; public String a; protected String b; String c; private String d; public Person(String name, int age) { this.name = name; this.age = age; } public Person() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", a='" + a + '\'' + ", b='" + b + '\'' + ", c='" + c + '\'' + ", d='" + d + '\'' + '}'; }
标签:String,Person,age,public,获取,Method,Constructor,Class,name From: https://www.cnblogs.com/yuzong/p/16721490.html