反射的简单应用

反射:1.反射机制概念
在Java中的反射机制是指在运行状态中,对于任意一个类都能够知道这个类所有的属性和方法;并且对于任意一个对象,都能够调用它的任意一个方法;这种动态获取信息以及动态调用对象方法的功能成为Java语言的反射机制。
2.反射的应用场合
在Java程序中许多对象在运行是都会出现两种类型:编译时类型和运行时类型。
编译时的类型由声明对象时实用的类型来决定,运行时的类型由实际赋值给对象的类型决定

获取Class对象的三种方法:
//使用第一种方法获取字节码文件.class
Student student=new Student();
Class c=student.getClass();
System.out.println©;
//使用第二种方式
Class c1 = Student.class;
System.out.println(c1);
//第三种方式
Class c2 = Class.forName(“com.offfcn.entity.Student”);

获取Class对象的无参构造方法:
Constructor constructor = c2.getConstructor(null);
constructor.newInstance(null);
获取Class对象的有参构造方法:
Constructor constructor = c2.getConstructor(int.class,String.class);
Object oj = constructor.newInstance(1,“22”);
获取私有的构造方法:
Constructor constructorpri=c2.getDeclaredConstructor(String.class);
constructorpri.setAccessible(true);
oj=constructorpri.newInstance(“3”);
Student student1=(Student) oj;
student1.print();
获取student类里面公有的属性:
Field[] fields = c2.getFields();
for (int i=0;i<fields.length;i++){
System.out.println(fields[i]);
}
获取所有(公有与私有)的属性:
Field[] df = c2.getDeclaredFields();
for (int i=0;i<df.length;i++){
System.out.println(df[i]);
给私有的属性赋值:
Field sname = c2.getDeclaredField(“sname”);
sname.setAccessible(true);/
//第一个参数是你要赋值的对象,第二个参数是你要赋值的具体的值
Object obj = c2.getConstructor().newInstance(null);
Student student2=(Student) obj;
sname.set(student2,“fdf”);
System.out.println(student2.getSname());
获取所有的公有方法:
Method[] m=c2.getMethods();
for (int i=0;i<m.length;i++){
System.out.println(m[i]);
获取所有(包括公有与私有)的方法:
Method[] mm = c2.getDeclaredMethods();
for (int i=0;i<mm.length;i++){
System.out.println(mm[i])
获取某一个公有的方法,并调用:
Method method=c2.getMethod(“add”);
method.invoke(c2.getConstructor().newInstance(null),null);
获取私有的方法:
单个方法,并调用
Method delete = c2.getDeclaredMethod(“delete”,String.class);
delete.setAccessible(true);//暴力获取私有方法
Object res = delete.invoke(c2.getConstructor().newInstance(null), “234”);
System.out.println(res);
//用反射来忽视泛型
List list=new ArrayList();
list.add(“qqq”);
list.add(“dd”);
list.add(“sa”);
//获取其class文件
Class classlist=list.getClass();
Method add = classlist.getMethod(“add”,Object.class);
add.invoke(list,1);
for (Object o:list
) {
System.out.println(o);
}
//实例化对象都走构造方法
/
—获取所有公有构造方法–*/
Constructor[] constructors = c2.getConstructors();
for (int i=0;i<constructors.length;i++){
System.out.println(constructors[i]);
}
//获取所有方法–包括私有或公有的构造方法
Constructor[] declaredConstructors = c2.getDeclaredConstructors();
for (int i=0;i<declaredConstructors.length;i++){
System.out.println(declaredConstructors[i]);
}

猜你喜欢

转载自blog.csdn.net/weixin_42772943/article/details/82987778