Together to learn Java (XXIII) ----- reflection

Short step, a thousand miles; not small streams, into jianghai.

 

Java language foundation

 

Java reflection

Look at the positive operation, this class is instantiated, then use the class object to operate.

public class Apple {
	
	private int price;
	public int highprice;
	int lowprice;
	String name;
	
	public int getprice() {
		return price;
	}
	
	public void setprice(int price) {
		this.price = price;
	}
	
	public void sell(){
		System.out.println("All apples are selling!");
	}
	
	private void buy() {
		System.out.println("Buy apples!");
	}

	public static void main(String[] args) throws Exception {
		//正常调用
		Apple apple = new Apple();
		apple.setprice(5);
		System.out.println("apple's price is: " + apple.getprice());

	}

}

  

Using reflection, first obtain the file object bytecode class (.class)

Get bytecode file object in three ways.

Class cls = Class.forName("Testfather.Apple");
Class cls = Apple.class;
Class cls = apple.getClass(); 

1. Static method forName Class class, directly into a bytecode file object class, then the class source file, or stage, and does not become the byte code file.

Class cls = Class.forName("Testfather.Apple"); 

2. When the class is loaded into .class files, this time into a .class Person class, acquiring the bytecode file object, i.e. gets its own, in the class bytecode stage.

Class cls = Apple.class;

Example 3. By acquiring the class bytecode class file object class creates objects in stages.

Class cls = apple.getClass();

  

Guess you like

Origin www.cnblogs.com/smilexuezi/p/11983490.html