package com.heyinchun.reflect;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Properties;
// 反射操作
import org.junit.Test;
@Deprecated // 弃用注解
class Teacher implements Runnable, Serializable {
public static String school = "songshu";
public static void test() {
System.out.println("static .......");
}
private String name;
private int age;
private String gender;
public Teacher() {
}
public Teacher(String name, int age, String gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
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;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + ", gender=" + gender + "]";
}
public void lesson(String content, int hours) {
String string = name + "老师上" + content + ",共上了" + hours + "小时";
System.out.println(string);
// throw new RuntimeException("sada");
}
public void study() {
}
@Override
public void run() {
}
}
public class ReflectTest {
@Test// 反射调用静态的属性和方法
public void test15() throws NoSuchFieldException, SecurityException {
try {
Class<?> class1 = Class.forName("com.heyinchun.reflect.Teacher");
try {
Object object = class1.newInstance();
Field schoolField = class1.getDeclaredField("school");
System.out.println(schoolField);
// 静态的不需要传对象
Object value = schoolField.get(null);
System.out.println(value);
// 静态的不需要传对象
schoolField.set(null, "松鼠");
Object value2 = schoolField.get(null);
System.err.println(value2);
try {
Method method = class1.getMethod("test");
try {
method.invoke(object);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void test14() {
try {
Class<?> class1 = Class.forName("com.heyinchun.reflect.Teacher");
Class<?> superclass = class1.getSuperclass();
System.out.println(superclass);
Class<?>[] interfaces = class1.getInterfaces(); // 获取事项的接口的类模板
for (int i = 0; i < interfaces.length; i++) {
System.out.println(interfaces[i]);
}
System.out.println("***************************");
// 获取所有公有方法
Method[] methods = class1.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println("___________________________________");
// 获取所有私有方法
Method[] declaredMethods = class1.getDeclaredMethods();
for (Method method : declaredMethods) {
System.out.println(method);
}
System.out.println("**********************");
Field[] fields = class1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
// 获取注解
System.out.println("*****************************");
Deprecated annotation = class1.getAnnotation(Deprecated.class);
System.out.println(annotation);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 调用私有方法
@Test // 非法实参错误,类型不对应 被调用的目标中有异常是会出的异常
public void test13() throws ClassNotFoundException, IllegalArgumentException, InvocationTargetException {
Class<?> class1 = Class.forName("com.heyinchun.reflect.Teacher");
try {
Object object = class1.newInstance();
try {
// 获取protect,private
Method lessonMethod1 = class1.getDeclaredMethod("lesson", String.class, int.class);
// 获取public方法
lessonMethod1.setAccessible(true);
// 调用方法
lessonMethod1.invoke(object, "Mysql", 12);// 第一个参数是对象。后面为参数
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 调用共有方法
@Test // 非法实参错误,类型不对应 被调用的目标中有异常是会出的异常
public void test12() throws ClassNotFoundException, IllegalArgumentException, InvocationTargetException {
Class<?> class1 = Class.forName("com.heyinchun.reflect.Teacher");
try {
Object object = class1.newInstance();
try {
// 获取protect,private
Method lessonMethod1 = class1.getDeclaredMethod("lesson", String.class, int.class);
// 获取public方法
Method lessonMethod = class1.getMethod("lesson", String.class, int.class);
// 调用方法
lessonMethod.invoke(object, "Mysql", 12);// 第一个参数是对象。后面为参数
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void test11() throws ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> clazz1 = Class.forName("com.heyinchun.reflect.Teacher");
// Object newInstance = clazz1.newInstance();
// 获取类的构造器对象,需要形参列表
Constructor<?> constructor = clazz1.getConstructor(String.class, int.class, String.class); // 参数中的列表是方法的形参的数据类型
Object object = constructor.newInstance("张三", 12, "女"); // 括号中式参数是实参列表
System.out.println(object);
}
@Test
public void test10() throws IOException {
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream("com/heyinchun/homework/test.properties");
Properties properties = new Properties();
// 用properties文件
properties.load(resourceAsStream);
// 获取配置文件中所有的key
Enumeration<?> propertyNames = properties.propertyNames();
while (propertyNames.hasMoreElements()) {
Object key = propertyNames.nextElement();
Object value = properties.get(key);
System.out.println(key + "====" + value);
}
}
@Test
public void test9() throws IOException {
// 获取当前类的类加载器
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream = classLoader
.getResourceAsStream("com/sun/corba/se/impl/logging/LogStrings.properties"); // 读取文件的路径 classPath环境变量
Properties properties = new Properties();
properties.load(inputStream);
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
Object key = names.nextElement();
Object value = properties.get(key);
System.out.println(key + "=" + value);
}
}
@Test
public void test8() throws IOException {
// 获取当前类的类加载器
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("test.properties"); // 读取文件的路径 classPath环境变量
Properties properties = new Properties();
properties.load(inputStream);
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
Object nextElement = names.nextElement();
Object object = properties.get(nextElement);
System.out.println(nextElement + " ^^^^^^^^^^^^^^^^^^^^^^^^^^^^" + object);
}
}
@Test
public void test7() {
// 引导类加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
// 扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
// 系统类加载器
ClassLoader bootstrapClassLoader = parent.getParent();
System.out.println(bootstrapClassLoader);
// 双亲委派,双亲就是扩展类加载器 和引导类加载器
// 子类加载器要先委派父类加载器加载吗,如果父类加载器能加载,由父类加载器加载,如果父类加载器拒绝加载,再返回给子类
// 加载器加载, 安全
}
@Test
public void test6() {
Class clazz1 = String.class;
Class class2 = Integer.class;
Class class3 = int.class;
System.out.println(class2);
System.out.println(class3);
// 是不是基本型
boolean primitive = class3.isPrimitive();
System.out.println(primitive);
System.out.println(double.class);
System.out.println(Double.class);
}
@Test
public void test5() throws ClassNotFoundException {
// 1)第一种放式获取类模板
Class clazz = Teacher.class;
// 2)第二种
Class class1 = new Teacher().getClass();
System.out.println(class1 == clazz);
// 3 第三种
Class<?> class2 = Class.forName("com.heyinchun.reflect.Teacher");
// 4 第四种
ClassLoader classLoader = this.getClass().getClassLoader();
ClassLoader classLoader2 = ReflectTest.class.getClassLoader();
System.out.println(classLoader);
System.out.println(classLoader2);
Class<?> class3 = classLoader.loadClass("com.heyinchun.reflect.Teacher");
System.err.println(class2 = class3);
}
// 暴力反射
@Test
public void test4() {
try {
Class<?> clazz = Class.forName("com.heyinchun.reflect.Teacher");
try {
Object object = clazz.newInstance();
try {
// Field nameField = clazz.getField("name"); 只能获取公共本类属性及父类的属性
// nameField.set(object, "张三");
Field nameField = clazz.getDeclaredField("name"); // 获取本类中所有声明的属性,包括私有的,公共的,被保护的都行
System.out.println(nameField);
// 设置可访问,突破封装 ,暴力反射!!!!
nameField.setAccessible(true);
nameField.set(object, "张三");
System.out.println(object);
// 属性名写错,或者是私有属性
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 没有无参构造器
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// 无法访问私有成员时
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 反射避免类不见时,编译出错 new 对象时 类不见的话就会出错!
*/
@Test // 类找不到异常
public void test2() throws ClassNotFoundException {
try {
// 手工加载类 类即使不存在,也能编译,这是软编码
Class forName = Class.forName("com.heyinchun.reflect.Teacher"); // 类加载时必须使用全限定类名
Object object = forName.newInstance(); // 通过类模板对象来创建实体对象,调用无参构造器
System.out.println(object);
// 访问对象的属性,先获取属性定义对象,在配合this对象完成对象访问
try {
Field namefield = forName.getField("name");
System.out.println(namefield);
// object.name ="张三";
// 反射赋值name
namefield.set(object, "张三");
Object name = namefield.get(object);
System.out.println(name);
Field ageField = forName.getField("age");
ageField.set(object, 14);
Object age = ageField.get(object);
System.out.println(age);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 类中没有无参构造器时的异常 // 成员私有的时候访问的异常
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void test1() {
// 在编译时强烈的依赖类,这种编码方式硬编码
Teacher teacher1 = new Teacher("张三", 12, "男");
Teacher teacher2 = new Teacher("李四", 12, "女");
// System.out.println(teacher1.name);
// System.out.println(teacher2.gender);
System.out.println(teacher1);
System.out.println(teacher2);
}
}