Java-反射Reflection每日一考
1.写出获取Class实例的三种常见方式
package www.Reflection; import org.junit.Test; import java.lang.reflect.Constructor; public class ReflectionTest { @Test public void test() throws Exception{ //1.调用无参构造器,获取Employee类的对象 Class employeeClass1 = Employee.class; Object o = employeeClass1.newInstance(); //2.根据类全名获取相应Class对象 Class employeeClass2 = Class.forName("www.Reflection.Employee"); //3.调用指定参数结构的构造器,生成Constructor的实例 Constructor constructor = employeeClass1.getConstructor(String.class);
//3.已知某个类的实例,调用改实例的getClass方法获取Class对象 Class employeeClass2 = “www.Reflection.Employee”.getClass
//4.使用类构造器 ClassLoader classLoader = ReflectionTest.class.getClassLoader(); Class c = classLoader.loadClass("www.Reflection.Employee"); } }
2.谈谈你对Class类的理解
Class实例对应着加载到内存中的一个运行时类。
3.创建Class对应运行时类的对象的通用方法,代码实现。以及这样操作,需要对应的运行时类构造器方面满足的要求。
//1.得到一个Class类实例 Class c2 = new Employee().getClass(); //2.创建运行时类的对象 Employee e = (Employee) c2.newInstance();
要求:这个运行时的类必须有空参的构造器;这个构造器的权限通常为public
4.在工程或module的src下有名为”jdbc.properties”的配置文件,文件内容为:name=Tom。如何在程序中通过代码获取Tom这个变量值。代码实现
方式①创建文件流FileInputStream
方式②使用ClassLoder
InputStream in = null; in=this.getClass().getClassLoader().getResourceAsStream("exer2\\test.properties"); System.out.println(in)
5. 如何调用方法show()
//1.得到一个Class类实例 Class c2 = new Employee().getClass(); //2.创建运行时类的对象 Employee e = (Employee) c2.newInstance(); //获取运行时类中指定变量名的属性 Field name = c2.getDeclaredField("name"); name.set(e,"fengfeng"); System.out.println(e.getName()); //调用getname Method getname = c2.getDeclaredMethod("getName"); //保证当前属性是可访问的 name.setAccessible(true); Object invoke = getname.invoke(e, null); System.out.println(invoke);