Learning Notes - Day 17 18 (Reflection)

reflex

What is Reflection

Learning reflex:

  • Reflection is the behavior of the runtime

  • Class Class:
    An instance object generated by this class is used to describe a class. The class object describes the Student class.

  • All Student objects and Student classes share the current class object

  • Examples: class "hehe" and "hip-hop" String classes share the class object

Get the class object

Three species:

  • 1: Class. forName (full-qualified package name of class required; class name); most common
  • 2: class name.
  • 3: Object. getClass
  • 4:class object. getSuperClass gets the class object of the parent class
public class Test02 {
	public static void main(String[] args) throws ClassNotFoundException {
		
		//Method of Getting Class Objects of a Class
		Class clz = Class.forName("java.lang.String");
		System.out.println(clz);
		
		//Get String's lass object
		Class clz1 = String.class;
		
		System.out.println(clz==clz1);
		//Get the Class object corresponding to the String object
		Class clz2 = "zhangsan".getClass();
		Class clz3 = "lisi".getClass();
		
		System.out.println(clz1==clz2);
		System.out.println(clz2==clz3);
		
		
		System.out.println(clz3.getSuperclass());
	}
}

Getting Attribute Method Constructor

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/*
 * 
 *   Class What can an object do?
 *   	 Get the Class object corresponding to User and then.
 */
public class Test03 {
	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, NoSuchMethodException {
		
		//Get the class object of User
		Class clz = Class.forName("com.mage.reff.User");
		
		
		//get attribute
		System.out.println("Obtain public Modified specified attributes");
		Field f = clz.getField("id");
		System.out.println(f.getName()+"=="+f.getType()+"=="+Modifier.toString(f.getModifiers()));
		
		System.out.println("Obtain public All attributes of the specified modifier");
		Field[] fs = clz.getFields();
		for(Field ff:fs) {
			System.out.println(ff.getName()+"=="+ff.getType()+"=="+Modifier.toString(ff.getModifiers()));
		}
		
		System.out.println("Gets all specified properties");
		f = clz.getDeclaredField("name");
		System.out.println(f.getName()+"=="+f.getType()+"=="+Modifier.toString(f.getModifiers()));
		
		System.out.println("Get all attributes");
		fs = clz.getDeclaredFields();
		for(Field ff:fs) {
			System.out.println(ff.getName()+"=="+ff.getType()+"=="+Modifier.toString(ff.getModifiers()));
		}
		
		System.out.println("Obtain public Getting the parent class's");
		Method[] ms = clz.getMethods();
		for(Method mm:ms) {
			System.out.println(Modifier.toString(mm.getModifiers())+"=="+mm.getParameterCount()+"=="+mm.getName());
		}
		System.out.println("Obtain public Designation method of revision  ");
		Method m = clz.getMethod("fun", Integer.TYPE,String.class);
		System.out.println(Modifier.toString(m.getModifiers())+"=="+m.getParameterCount()+"=="+m.getName());
		
		System.out.println("Gets all methods that do not contain parent classes");
		ms = clz.getDeclaredMethods();
		for(Method mm:ms) {
			System.out.println(Modifier.toString(mm.getModifiers())+"=="+mm.getParameterCount()+"=="+mm.getName());
		}
		System.out.println("Get specified non public Modification methods  ");
		m = clz.getDeclaredMethod("method", Integer.TYPE,String.class);
		System.out.println(Modifier.toString(m.getModifiers())+"=="+m.getParameterCount()+"=="+m.getName());
		
		
		System.out.println("Get the constructor public");
		Constructor c = clz.getConstructor(null);
		System.out.println(c.getName()+"=="+c.getParameterCount());
		
		System.out.println("Get constructor non public");
		c = clz.getDeclaredConstructor(Integer.TYPE,String.class,Integer.TYPE,Integer.TYPE);
		System.out.println(c.getName()+"=="+c.getParameterCount());
		
		System.out.println("Get all constructors public");
		Constructor[] cs = clz.getConstructors();
		
		for(Constructor cc:cs) {
			System.out.println(cc.getName()+"=="+cc.getParameterCount());
		}
		
		System.out.println("Get all constructors");
		cs = clz.getDeclaredConstructors();
		
		for(Constructor cc:cs) {
			System.out.println(cc.getName()+"=="+cc.getParameterCount());
		}
	}
}

implement

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//Creating Objects Using Reflection Call Constructor
// When calling a non-public decorated constructor with reflection, you need to cancel the check
public class Test04 {
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		
		//Get the Class object for User
		Class clz = User.class;
		
		//Gets the specified constructor corresponding to user
		Constructor c = clz.getDeclaredConstructor(Integer.TYPE,String.class,Integer.TYPE,Integer.TYPE);
		
		//Cancel inspection
		c.setAccessible(true);
		//Invoking Constructors
		User u = (User) c.newInstance(12,"Hey",11,11);
		c.setAccessible(false);
		
		System.out.println(u);
	}
}

The effect of reflection on singletons

public class Lazy {
	
	private static Lazy lazy ;
	
	private Lazy() {
		if(lazy!=null) {
			throw new RuntimeException("Let's make you fuck me");
		}
	}
	
	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 establish 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  Export Class objects for each element in a collection object
	 * @param ls	Exported Collection Objects
	 * @param fileName  The name of the exported file
	 * @param filePath  Exported file path
	 * @param titls		Title of export file
	 * @param fieldName	 Export each attribute name of an object in a collection
	 * @throws IllegalAccessException Property is invisible to throw the exception
	 * @throws IllegalArgumentException  Illegal parameter anomaly
	 * @throws IOException Connection error
	 */
	public static void export(Class<?> clz,List<?> ls,String fileName,String filePath,String[] titls,String[] fieldName) throws IllegalArgumentException, IllegalAccessException, IOException  {
		//Create workbook objects
		Workbook wb = new HSSFWorkbook();
		
		//Create stream objects
		FileOutputStream fs = new FileOutputStream(filePath+File.separator+fileName);
		
		//Create sheet
		Sheet sheet = wb.createSheet(fileName.substring(0,fileName.indexOf(".")));
		
		//Create row
		Row rowTitle = sheet.createRow(0);//Header
		
		//Creating Cells
		for(int i = 0;i<titls.length;i++) {
			//Creating Cells
			Cell cell = rowTitle.createCell(i);
			//Fill value
			cell.setCellValue(titls[i]);
		}
		
		//Add a data loop to create a List length row
		for(int i =0;i<ls.size();i++) {
			//Create row
			Row rowData = sheet.createRow(i+1);//Row data
			Field[] f = clz.getDeclaredFields();
			for(int j = 0;j<titls.length;j++) {
				//Creating Cells
				Cell cell = rowData.createCell(j);
				//Gets the name of the property
				f[j].setAccessible(true);
				cell.setCellValue(f[j].get(ls.get(i)).toString());
				f[j].setAccessible(false);
			}
		}
		
		//Write out
		wb.write(fs);
		//Close
		fs.close();
		wb.close();
	}
	
	
	public static void main(String[] args) throws Exception {
		
		List<Student> ls = new ArrayList<>();
		ls.add(new Student("Zhang three 1", 1, 1, 78));
		ls.add(new Student("Zhang three 2", 4, 2, 68));
		ls.add(new Student("Zhang three 3", 2, 1, 98));
		ls.add(new Student("Zhang three 5", 3, 2, 18));
		ls.add(new Student("Zhang three 4", 5, 1, 38));
		
		export(Student.class,ls,"report card.xls","C:\\Users\\wawjy\\Desktop",new String[] {"Full name","Student ID","Gender","achievement"},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("Student achievement.xls");
	    
	    //Create sheet
	    Sheet sheet = wb.createSheet("report card");
	    //Create row
	    Row row = sheet.createRow(0);
	    //Creating Cells
	    Cell cell1 = row.createCell(0);
	    //Creating Cells
	    Cell cell2 = row.createCell(1);
	    
	    //Fill value
	    cell1.setCellValue("Full name");
	    cell2.setCellValue("achievement");
	    
	    
	    wb.write(fileOut); 
	    fileOut.close();
	    wb.close();
	}
}	

Tags: Java Apache Attribute xml

Posted on Sat, 12 Oct 2019 11:40:56 -0700 by daveoffy