Java 反射 使用總結

轉載請標明出處:http://www.cnblogs.com/zhaoyanjun/p/6074887.html1
本文出自【趙彥軍的博客】html

反射機制是什麼

反射機制是在運行狀態中,對於任意一個類,都可以知道這個類的全部屬性和方法;對於任意一個對象,都可以調用它的任意一個方法和屬性;這種動態獲取的信息以及動態調用對象的方法的功能稱爲java語言的反射機制。java

反射機制能作什麼

反射機制主要提供瞭如下功能:json

  • 在運行時判斷任意一個對象所屬的類;
  • 在運行時構造任意一個類的對象;
  • 在運行時判斷任意一個類所具備的成員變量和方法;
  • 在運行時調用任意一個對象的方法;
  • 生成動態代理。

反射機制的相關API

**InterFace **接口api

package com.app;

public interface InterFace {

	void read() ;
	
}

Person 類數組

package com.app;

public class Person  implements InterFace {

	private String id ;

	private String name ;

	public String age ;
	
	//構造函數1
	public Person( ){

	}

	//構造函數2
	public Person( String id ){
		this.id = id ;
	}

	//構造函數3
	public Person( String id  , String name ){
		this.id = id ;
		this.name = name ;
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}


	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	/**
	 * 靜態方法
	 */
	public static void update(){

	}


	@Override
	public void read() {

	}

}
  • 獲取類:3種方法
package com.app;

public class T1 {

	public static void main(String[] args) {

		//第一種方法:forName
		try {
			Class<?> class1 = Class.forName("com.app.Person");

			System.out.println( class1 );
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}


		//第二張方法:class
		Class<?> class2 = Person.class;  

		//第三種方法:getClass
		Person person = new Person();  
		Class<?> class3 = person.getClass();

		System.out.println( class2 );
		System.out.println( class3 );
	}

}

運行結果:安全

class com.app.Person
class com.app.Person
class com.app.Person
  • 獲取全部的方法:getMethods( )
package com.app;

import java.lang.reflect.Method;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//獲取全部的公共的方法
			Method[] methods = 	class1.getMethods() ;
			
			for (Method method : methods) {
				System.out.println( method );
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

運行結果:app

//自定義方法
public static void com.app.Person.update()
public java.lang.String com.app.Person.getName()
public void com.app.Person.read()
public java.lang.String com.app.Person.getId()
public void com.app.Person.setName(java.lang.String)
public void com.app.Person.setId(java.lang.String)

//父類Object類方法
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
  • 獲取全部實現的接口:getInterfaces()
package com.app;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//獲取全部的接口
			Class<?>[] interS = class1.getInterfaces() ;

			for (Class<?> class2 : interS ) {
				System.out.println( class2 );
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

運行結果:ide

interface com.app.InterFace
  • 獲取父類:getSuperclass()
package com.app;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//獲取父類
			Class<?> superclass = class1.getSuperclass() ;

			System.out.println( superclass );

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

運行結果:函數

//父類是Object類
class java.lang.Object
  • 獲取全部的構造函數:getConstructors()
package com.app;

import java.lang.reflect.Constructor;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//獲取全部的構造函數
			Constructor<?>[] constructors = class1.getConstructors() ;

			for (Constructor<?> constructor : constructors) {
				System.out.println( constructor );
			}


		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

運行結果:this

public com.app.Person(java.lang.String,java.lang.String)
public com.app.Person(java.lang.String)
public com.app.Person()
  • 獲取全部的屬性:getDeclaredFields();
package com.app;

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

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//取得本類的所有屬性
			Field[] field = class1.getDeclaredFields();

			for (Field field2 : field) {
				System.out.println( field2 );
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

運行結果:

private java.lang.String com.app.Person.id
private java.lang.String com.app.Person.name

能夠看出屬性的修飾符是: private , 數據類型:String ,名字:id/name

  • 建立實例:newInstance()
package com.app;


public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");;

			//建立實例化:至關於 new 了一個對象
			Object object = class1.newInstance() ;

			//向下轉型
			Person person = (Person) object ;

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}
}

getDeclaredFields 和 getFields 的區別

getDeclaredFields()得到某個類的全部申明的字段,即包括public、private和proteced,可是不包括父類的申明字段。

getFields()得到某個類的全部的公共(public)的字段,包括父類。

小例子

package com.app;

import java.lang.reflect.Field;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");;

			//得到全部的字段屬性:包括 
			Field[] declaredFields = class1.getDeclaredFields() ;

			Field[] fields = class1.getFields() ;

			for( Field field : declaredFields ){
				System.out.println( "de--  " +  field  );
			}

			for( Field field : fields ){
				System.out.println( "fields--  " +  field  );
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

de--  private java.lang.String com.app.Person.id
de--  private java.lang.String com.app.Person.name
de--  public java.lang.String com.app.Person.age
fields--  public java.lang.String com.app.Person.age

實戰1:經過反射,獲取對象實例,而且操做對象的方法

package com.app;


public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");;

			//建立實例化:至關於 new 了一個對象
			Object object = class1.newInstance() ;

			//向下轉型				
			Person person = (Person) object ;
			
			person.setId( "100");
			person.setName( "jack") ; 
			
			System.out.println( "id: " + person.getId() + " name: " + person.getName()  );
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

id: 100 name: jack

實戰2:經過反射獲取對象字段屬性,而且賦值

package com.app;

import java.lang.reflect.Field;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//建立實例
			Object person = class1.newInstance();

			//得到id 屬性
			Field idField = class1.getDeclaredField( "id" ) ;
			
			//給id 屬性賦值
			idField.set(  person , "100") ;

			//打印 person 的屬性值
			System.out.println( idField.get( person ));

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

java.lang.IllegalAccessException: Class com.app.T1 can not access a member of class com.app.Person with modifiers "private"
	at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
	at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(Unknown Source)
	at java.lang.reflect.AccessibleObject.checkAccess(Unknown Source)
	at java.lang.reflect.Field.set(Unknown Source)
	at com.app.T1.main(T1.java:20)

程序崩潰,緣由是:id 這個屬性的是 private 私有的,不能修改它的值。

改進:

添加 idField.setAccessible( true );

完整的代碼爲:

package com.app;

import java.lang.reflect.Field;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//建立實例
			Object person = class1.newInstance();

			//得到id 屬性
			Field idField = class1.getDeclaredField( "id" ) ;

			//打破封裝  實際上setAccessible是啓用和禁用訪問安全檢查的開關,並非爲true就能訪問爲false就不能訪問  
            //因爲JDK的安全檢查耗時較多.因此經過setAccessible(true)的方式關閉安全檢查就能夠達到提高反射速度的目的  
			idField.setAccessible( true );
			
			//給id 屬性賦值
			idField.set(  person , "100") ;

			//打印 person 的屬性值
			System.out.println( idField.get( person ));

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

100

實戰3:綜合訓練,反射操做屬性和方法

package com.app;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//建立實例
			Object person = class1.newInstance();

			//得到id 屬性
			Field idField = class1.getDeclaredField( "id" ) ;

			//打破封裝  實際上setAccessible是啓用和禁用訪問安全檢查的開關,並非爲true就能訪問爲false就不能訪問  
			//因爲JDK的安全檢查耗時較多.因此經過setAccessible(true)的方式關閉安全檢查就能夠達到提高反射速度的目的  
			idField.setAccessible( true );

			//給id 屬性賦值
			idField.set(  person , "100") ;

			//獲取 setName() 方法
			Method setName = class1.getDeclaredMethod( "setName", String.class ) ;
			//打破封裝 
			setName.setAccessible( true );

			//調用setName 方法。
			setName.invoke( person , "jack" ) ;

			//獲取name 字段
			Field nameField = class1.getDeclaredField( "name" ) ;
			//打破封裝 
			nameField.setAccessible( true );

			//打印 person 的 id 屬性值
			String id_ = (String) idField.get( person ) ;
			System.out.println( "id: " + id_ );

			//打印 person 的 name 屬性值
			String name_ = ( String)nameField.get( person ) ;
			System.out.println( "name: " + name_ );
			
			//獲取 getName 方法
			Method getName = class1.getDeclaredMethod( "getName" ) ;
			//打破封裝 
			getName.setAccessible( true );
			
			//執行getName方法,而且接收返回值
			String name_2 = (String) getName.invoke( person  ) ;
			System.out.println( "name2: " + name_2 );

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

id: 100
name: jack
name2: jack

實戰4:靜態屬性、靜態方法調用

定義 Util 類

package com.app;

public class Util {

	public static String name = "json" ;

	/**
	 * 沒有返回值,沒有參數
	 */
	public static void getTips(){
		System.out.println( "執行了---------1111");
	}

	/**
	 * 有返回值,沒有參數
	 */
	public static String getTip(){
		System.out.println( "執行了---------2222");
		return "tip2" ;
	}

	/**
	 * 沒有返回值,有參數
	 * @param name
	 */
	public static void getTip( String name ){
		System.out.println( "執行了---------3333 參數: " + name );
	}

	/**
	 * 有返回值,有參數
	 * @param id
	 * @return
	 */
	public static String getTip( int id ){
		System.out.println( "執行了---------4444 參數: " + id );
		if ( id == 0 ){
			return "tip1 444 --1 " ;
		}else{
			return "tip1 444 --2" ;
		}
	}

}

完整小例子:

package com.app;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class T1 {

	public static void main(String[] args) {

		try {
			//建立類
			Class<?> class1 = Class.forName("com.app.Util");

			//獲取 nameField 屬性
			Field nameField = class1.getDeclaredField( "name" ) ;
			//獲取 nameField 的值
			String name_ = (String) nameField.get( nameField ) ;
			//輸出值
			System.out.println( name_ );


			//沒有返回值,沒有參數
			Method getTipMethod1 = class1.getDeclaredMethod( "getTips"  ) ; 
			getTipMethod1.invoke( null  ) ;
			
			//有返回值,沒有參數
			Method getTipMethod2 = class1.getDeclaredMethod( "getTip"  ) ; 
			String result_2 = (String) getTipMethod2.invoke( null  ) ;
			System.out.println( "返回值: "+ result_2 );
			
			//沒有返回值,有參數
			Method getTipMethod3 = class1.getDeclaredMethod( "getTip" , String.class  ) ; 
			String result_3 = (String) getTipMethod3.invoke( null , "第三個方法"  ) ;
			System.out.println( "返回值: "+ result_3 );
			
			//有返回值,有參數
			Method getTipMethod4 = class1.getDeclaredMethod( "getTip" , int.class ) ; 
			String result_4 = (String) getTipMethod4.invoke( null  , 1 ) ;
			System.out.println( "返回值: "+ result_4 );
			
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果:

json
執行了---------1111
執行了---------2222
返回值: tip2
執行了---------3333 參數: 第三個方法
返回值: null
執行了---------4444 參數: 1
返回值: tip1 444 --2

當參數是 int 類型 和 Integer 類型,反射獲取方法不同

  • 當參數是 int 類型時
/**
	 * 沒有返回值,有參數
	 * @param id
	 */
	public static void getTip( int id ){
		
	}

獲取方法的時候須要用:int.class。不能使用 Integer.class. 會報錯。

Method getTipMethod4 = class.getDeclaredMethod( "getTip" , int.class ) ; 
String result_4 = (String) getTipMethod4.invoke( null  , 1 ) ;
System.out.println( "返回值: "+ result_4 );
  • 當參數是 Integer類型時
/**
	 * 沒有返回值,有參數
	 * @param id
	 */
	public static void getTip( Integer id ){
		
	}

獲取方法的時候須要用:Integer .class。不能使用 int.class. 會報錯。

Method getTipMethod4 = class.getDeclaredMethod( "getTip" , Integer .class ) ; 
String result_4 = (String) getTipMethod4.invoke( null  , 1 ) ;
System.out.println( "返回值: "+ result_4 );

建立對象實例

Person 類

package com.app;

public class Person{

	private String id ;

	private String name ;


	//構造函數1
	public Person( ){
		System.out.println( "構造函數  無參" );
	}

	//構造函數2
	public Person( String id ){
		this.id = id ;
		System.out.println( "構造函數 id : " + id );
	}

	//構造函數3
	public Person( String id  , String name ){
		this.id = id ;
		this.name = name ;
		System.out.println( "構造函數 id : " + id  + " name: " + name );
	}


	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

建立實例實戰

package com.app;

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

public class T1 {

	public static void main(String[] args) {

		try {
			
			//建立類
			Class<?> class1 = Class.forName("com.app.Person");

			//無參構造函數
			Object object = class1.newInstance() ;
			
			//有參構造函數:一個參數
			Constructor<?> constructor =  class1.getDeclaredConstructor( String.class ) ;
			constructor.newInstance( "1000" ) ;
			
			//有參構造函數:二個參數
			Constructor<?> constructor2 =  class1.getDeclaredConstructor( String.class , String.class ) ;
			constructor2.newInstance( "1001" , "jack" ) ;

		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

	}
}

運行結果

構造函數  無參
構造函數 id : 1000
構造函數 id : 1001 name: jack

總結

  • Class類提供了四個public方法,用於獲取某個類的構造方法。
Constructor getConstructor(Class[] params)     根據構造函數的參數,返回一個具體的具備public屬性的構造函數
Constructor getConstructors()     返回全部具備public屬性的構造函數數組
Constructor getDeclaredConstructor(Class[] params)     根據構造函數的參數,返回一個具體的構造函數(不分public和非public屬性)
Constructor getDeclaredConstructors()    返回該類中全部的構造函數數組(不分public和非public屬性)
  • 四種獲取成員方法的方法
Method getMethod(String name, Class[] params)    根據方法名和參數,返回一個具體的具備public屬性的方法
Method[] getMethods()    返回全部具備public屬性的方法數組
Method getDeclaredMethod(String name, Class[] params)    根據方法名和參數,返回一個具體的方法(不分public和非public屬性)
Method[] getDeclaredMethods()    返回該類中的全部的方法數組(不分public和非public屬性)
  • 四種獲取成員屬性的方法
Field getField(String name)    根據變量名,返回一個具體的具備public屬性的成員變量
Field[] getFields()    返回具備public屬性的成員變量的數組
Field getDeclaredField(String name)    根據變量名,返回一個成員變量(不分public和非public屬性)
Field[] getDelcaredField()    返回全部成員變量組成的數組(不分public和非public屬性)
相關文章
相關標籤/搜索