反射
什么是反射
学习反射:
-
反射是运行期的行为
-
Class类:
这个类产生的一个实例对象用来描述某个类。 class 这个class对象描述的就是Student类。 -
所有的Student的对象和Student类共享 当前该class对象
-
举例: class “hehe” “嘻嘻” String类 都共享该class对象
获取class对象
三种:
- 1:Class.forName(需要获取类的全限定名包名.类名); 最常见的
- 2:类名.class
- 3:对象.getClass
- 4:class对象.getSuperClass 获取父类的class对象
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
//获取一个类的Class对象的方法
Class clz = Class.forName("java.lang.String");
System.out.println(clz);
//获取String的Class对象
Class clz1 = String.class;
System.out.println(clz==clz1);
//获取String对象对应的Class对象
Class clz2 = "zhangsan".getClass();
Class clz3 = "lisi".getClass();
System.out.println(clz1==clz2);
System.out.println(clz2==clz3);
System.out.println(clz3.getSuperclass());
}
}
获取属性 方法 构造器
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/*
*
* Class对象能做什么?
* 获取User对应的Class对象 然后.
*/
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException {
//获取User的class对象
Class clz = Class.forName("com.mage.reff.User");
//获取属性
System.out.println("获取public修饰的指定的属性");
Field f = clz.getField("id");
System.out.println(f.getName()+"=="+f.getType()+"=="+Modifier.toString(f.getModifiers()));
System.out.println("获取public修饰的指定的所有属性");
Field[] fs = clz.getFields();
for(Field ff:fs) {
System.out.println(ff.getName()+"=="+ff.getType()+"=="+Modifier.toString(ff.getModifiers()));
}
System.out.println("获取所有指定的属性");
f = clz.getDeclaredField("name");
System.out.println(f.getName()+"=="+f.getType()+"=="+Modifier.toString(f.getModifiers()));
System.out.println("获取所有属性");
fs = clz.getDeclaredFields();
for(Field ff:fs) {
System.out.println(ff.getName()+"=="+ff.getType()+"=="+Modifier.toString(ff.getModifiers()));
}
System.out.println("获取public修的所有方法 获取父类的");
Method[] ms = clz.getMethods();
for(Method mm:ms) {
System.out.println(Modifier.toString(mm.getModifiers())+"=="+mm.getParameterCount()+"=="+mm.getName());
}
System.out.println("获取public修的指定方法 ");
Method m = clz.getMethod("fun", Integer.TYPE,String.class);
System.out.println(Modifier.toString(m.getModifiers())+"=="+m.getParameterCount()+"=="+m.getName());
System.out.println("获取所有方法 不包含父类的");
ms = clz.getDeclaredMethods();
for(Method mm:ms) {
System.out.println(Modifier.toString(mm.getModifiers())+"=="+mm.getParameterCount()+"=="+mm.getName());
}
System.out.println("获取的指定非public修饰的方法 ");
m = clz.getDeclaredMethod("method", Integer.TYPE,String.class);
System.out.println(Modifier.toString(m.getModifiers())+"=="+m.getParameterCount()+"=="+m.getName());
System.out.println("获取构造器public");
Constructor c = clz.getConstructor(null);
System.out.println(c.getName()+"=="+c.getParameterCount());
System.out.println("获取构造器 非public");
c = clz.getDeclaredConstructor(Integer.TYPE,String.class,Integer.TYPE,Integer.TYPE);
System.out.println(c.getName()+"=="+c.getParameterCount());
System.out.println("获取所有的构造器 public");
Constructor[] cs = clz.getConstructors();
for(Constructor cc:cs) {
System.out.println(cc.getName()+"=="+cc.getParameterCount());
}
System.out.println("获取所有的构造器");
cs = clz.getDeclaredConstructors();
for(Constructor cc:cs) {
System.out.println(cc.getName()+"=="+cc.getParameterCount());
}
}
}
执行
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
//使用反射调用构造器 创建对象
// 使用反射调用某个非public修饰的构造器时 需要取消检查
public class Test04 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取User对于的Class对象
Class clz = User.class;
//获取user对应的指定构造器
Constructor c = clz.getDeclaredConstructor(Integer.TYPE,String.class,Integer.TYPE,Integer.TYPE);
//取消检查
c.setAccessible(true);
//调用构造器
User u = (User) c.newInstance(12,"嘿嘿",11,11);
c.setAccessible(false);
System.out.println(u);
}
}
反射对于单例的影响
public class Lazy {
private static Lazy lazy ;
private Lazy() {
if(lazy!=null) {
throw new RuntimeException("让你丫发我野");
}
}
public static Lazy getInstance() {
if(lazy==null) {
lazy=new Lazy();
}
return lazy;
}
public Object readResolve() {
return lazy;
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test05 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Lazy lazy = Lazy.getInstance();
Class clz = Lazy.class;
Constructor c = clz.getDeclaredConstructor(null);
c.setAccessible(true);
Lazy lazy1 = (Lazy) c.newInstance(null);
c.setAccessible(false);
System.out.println(lazy+"=="+lazy1+"=="+(lazy==lazy1));
}
}
POI建立xml
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ExportPoi {
/**
*
* @param clz 导出集合对象中每个元素的Class对象
* @param ls 导出的集合对象
* @param fileName 导出的文件名称
* @param filePath 导出的文件路径
* @param titls 导出文件的标题
* @param fieldName 导出集合中对象的每个属性名称(英文)
* @throws IllegalAccessException 属性的是不可见 抛出该异常
* @throws IllegalArgumentException 非法参数异常
* @throws IOException 连接错误
*/
public static void export(Class<?> clz,List<?> ls,String fileName,String filePath,String[] titls,String[] fieldName) throws IllegalArgumentException, IllegalAccessException, IOException {
//创建工作簿对象
Workbook wb = new HSSFWorkbook();
//创建流对象
FileOutputStream fs = new FileOutputStream(filePath+File.separator+fileName);
//创建sheet
Sheet sheet = wb.createSheet(fileName.substring(0,fileName.indexOf(".")));
//创建row
Row rowTitle = sheet.createRow(0);//表头
//创建单元格
for(int i = 0;i<titls.length;i++) {
//创建单元格
Cell cell = rowTitle.createCell(i);
//填充值
cell.setCellValue(titls[i]);
}
//添加数 据 循环创建List长度个row
for(int i =0;i<ls.size();i++) {
//创建row
Row rowData = sheet.createRow(i+1);//行数据
Field[] f = clz.getDeclaredFields();
for(int j = 0;j<titls.length;j++) {
//创建单元格
Cell cell = rowData.createCell(j);
//获取属性的名称
f[j].setAccessible(true);
cell.setCellValue(f[j].get(ls.get(i)).toString());
f[j].setAccessible(false);
}
}
//写出
wb.write(fs);
//关闭
fs.close();
wb.close();
}
public static void main(String[] args) throws Exception {
List<Student> ls = new ArrayList<>();
ls.add(new Student("张三1", 1, 1, 78));
ls.add(new Student("张三2", 4, 2, 68));
ls.add(new Student("张三3", 2, 1, 98));
ls.add(new Student("张三5", 3, 2, 18));
ls.add(new Student("张三4", 5, 1, 38));
export(Student.class,ls,"学生成绩单.xls","C:\\Users\\wawjy\\Desktop",new String[] {"姓名","学号","性别","成绩"},new String[] {"name","id","gender","score"});
}
}
class Student {
private String name;
private int id;
private int gender;
private int score;
public Student(String name, int id, int gender, int score) {
super();
this.name = name;
this.id = id;
this.gender = gender;
this.score = score;
}
public Student() {
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class Test01 {
public static void main(String[] args) throws Exception {
Workbook wb = new HSSFWorkbook();
OutputStream fileOut = new FileOutputStream("学生成绩.xls");
//创建sheet
Sheet sheet = wb.createSheet("学生成绩单");
//创建行
Row row = sheet.createRow(0);
//创建单元格
Cell cell1 = row.createCell(0);
//创建单元格
Cell cell2 = row.createCell(1);
//填充值
cell1.setCellValue("姓名");
cell2.setCellValue("成绩");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}