Java反射机制
1.何为反射
反射可以理解为一面镜子照射的实物的虚像映射回实物。在程序上即为通过实例化对象得到所属类的信息。
2.反射作用
Java反射机制可以动态获取程序信息和动态调用对象,即可以实现动态创建和动态编译对象。
1.1在运行状态中
(1)可以构造任意一个类的对象
(2)也可以获取任意一个对象所属类的信息
(3)甚至可以调用任意一个类成员变量和方法
(4)当然也可以获取任意一个对象的属性和方法
3.Class类实例化应用
3.1.进行Class类对象的实例化的三种方式
(1)依据全限类名;Class.forName(“全限定类名”)
Class<?> c=null;
c=Class.forName("com.item.类名");//com.item:所属包名
getName()方法可以获得包括所属包名的类名
getPackage()方法可以获取所属包名
(2)依据对象获取:对象名.getClass()
Class<?> c=null;
c=new 类名().getClass();
(3)依据类名获取:类名.class
Class<?> c=null;
c=类名.class;
3.2.Class类实例化其他类对象的两种方式
3.2.1.调用newInstance()通过无参构造方法实例化
package edu.day1;
import java.util.*;
public class Reflect {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Class<?> c=null;//?:占位符
try {
c=Class.forName("edu.day1.People");
}
catch (ClassNotFoundException e){
e.printStackTrace();
}
People peo=null;
peo=(People) c.newInstance();//实例化
peo.setName("张小凡");
peo.setNum(19);
System.out.println(peo);
}
}
class People{
private String name;
private int num;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public People() {
}
public People(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", num=" + num +
'}';
}
}
3.2.2.调用getConstructors()通过有参构造方法实例化
(1)getConstructors()获得实例化的类中全部构造方法
(2)获取有参构造方法对应的Constructor对象
(3)Constructor类实例化对象
package edu.day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Book {
public static void main(String[] args){
Class<?> c=null;
try {
c=Class.forName("edu.day1.BookReading");
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
BookReading book=null;
Constructor<?> constructor[] =null;//此处获得对象数组
constructor=c.getConstructors();//获取BookReading类的全部构造方法
try {
book=(BookReading) constructor[0].newInstance("碧瑶",19);//实例化BookReading对象
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
System.out.println(book);
}
}
class BookReading{
private String bookname;
private int index;
public BookReading(String bookname, int index) {
this.bookname = bookname;
this.index = index;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
@Override
public String toString() {
return "BookReading{" +
"bookname='" + bookname + '\'' +
", index=" + index +
'}';
}
}