1、返回字节码的三种方式
Class c = Class.forName("java.lang.String"); Class c1=Users.class; Class c2=new Users().getClass(); System.out.println(c2==c1); ==> true System.out.println(int.class==Integer.TYPE); ==>true |
2、概念:将java类的各种成分映射成响应的java类
Users users=new Users(); Field field=users.getClass().getDeclaredField("name"); //获取所有声明的变量,含私有的成员变量 field.setAccessible(true); //暴力反射 field.get(users); |
//替换所有字段中的某个字母 Class cls=Class.forName("com.cn.finance.pojo.Users") ; Object obj=cls.newInstance(); Field[] fields=cls.getDeclaredFields(); for(Field field:fields){ field.setAccessible(true); if(field.getType()==String.class){ String s=field.get(obj).toString().replaceAll("b","x"); field.set(obj,s); } } |
//方法的反射
String str1 = "abc"; Method method = str1.getClass().getMethod("charAt", int.class); System.out.println(method.invoke(str1, 1)); Method.invoke(null,1);如果method的方法第一个参数为null,表示调用静态方法。 |
3、数组反射
具有相同的数组维度和数组类型,则属于同一个字节码
int[] a1=new int[3]; int[] a2=new int[4]; int[][] a3=new int[2][3]; String[] a4=new String[4]; System.out.println(a1.getClass()==a2.getClass());==>true |
4、hashcode内存泄漏:某对象A被存到集合中,改变对象A中用来计算hashcode值的变量x,使用collection.remove(A)方法无法删除对象A,此时出现内存泄漏。
5、内省操作javabean
//获取某个属性的值
Users user = new Users(); String pro1 = "name"; PropertyDescriptor propertyDescriptor = new PropertyDescriptor(pro1, user.getClass()); Method method = propertyDescriptor.getReadMethod(); Object obj=method.invoke(user); System.out.println(obj); |
6、org.apache.commons.beanutils.BeanUtils
Users user = new Users(); BeanUtils.setProperty(user, "name", "math"); String s=BeanUtils.getProperty(user, "name"); //始终返回的是string System.out.println(s); |
Users users=new Users(); PropertyUtils.setProperty(users,"name","tt"); PropertyUtils.getProperty(users,"name"); //返回变量本身的类型 |
7、注解:相当于一个特殊的类
@Deprecated //声明某个方法已过时或废弃 @SuppressWarnings("deprecation") //忽略方法过时的提示 @Override |
使用注解:1、注解类 2、应用注解的类 3、对应用类进行反射操作的类
//元注解 @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AnnoTest { String color()default "green"; String value(); } |
@AnnoTest(color = "red",value = "and") public class ReflectDemo { public static void main(String[] args) throws Exception { if (ReflectDemo.class.isAnnotationPresent(AnnoTest.class)) { AnnoTest annoTest = ReflectDemo.class.getAnnotation(AnnoTest.class); System.out.println(annoTest.color()+","+annoTest.value()); } } } |