歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java反射介紹

Java反射介紹

日期:2017/4/19 14:16:58   编辑:Linux編程

反射是Java中的非常重要的一項機制,也稱做reflection。它讓Java在運行中對自身進行檢查,並能直接操作程序的內部屬性或方法。

反射機制中常用的類

Reflection api中的內部信息有很多包括:package、 type parameters、 superclass、 implemented interfaces、 inner classes、 outer classes、 fields、 constructors、 methods、 modifiers等
常用的類主要包括:

  1. Class:標示某個具體的類或接口
  2. Constructor:封裝了類的構造方法
  3. Method:提供關於類或接口的方法的信息
  4. Field:提供有關類或接口的屬性信息,以及對他的動態訪問權限

Class類:

Class本身就是一個類,Class是該類的名稱,也是反射的起點;
獲取Class的方法有:

  • getClass():調用通過指定類的對象調用;如:Class cl=str.getClass() 假設str是String對象,類屬性為String
  • getSuperClass():通過Class類調用;如:Class clsup=cl.getSuperClass() 因為String的父類為Object,此去得到類屬性為Object
  • Class.forName():Class中的靜態方法,通過將類名當參數調用:如Class cl2=Class.forName("java.lang.String");注意:此去加載類
  • .Class:通過類名進行調用:如:Class cl3=String.Class;注意:此去不加載類
  • 基本類型TYPE語法:包裝類的調用方法:Class cl4=Integer.TYPE

主要的方法有:

1,public static Class<?> forName(String className) :natice 方法,動態加載類。非常重要。
       如在sql中動態加載驅動程序:class.forName(sqlDriver);
2,public T newInstance() :根據對象的class新建一個對象,用於反射。非常重要。
       可用在反射中構建對象,調用對象方法:
       class doubleClass= class.forName("java.lang.Double");
       Object objDouble = doubleClass.newInstance();
       如在javaBean中就應用了這個方法,因為java默認要有一個無參構造函數。
3, public ClassLoader getClassLoader() :獲得類的類加載器Bootstrap  ,Extension ,System or user custom      ClassLoader(一般為system classloader)。重要。
4,public String getName() :獲取類或接口的名字。記住enum為類,annotation為接口。重要
5,public native Class getSuperclass():獲取類的父類,繼承了父類則返回父類,否則返回java.lang.Object。返回Object的父類為空-null。一般
6,public java.net.URL getResource(String name) :根據字符串獲得資源。
7,其他類 
 public boolean isEnum() :判斷是否為枚舉類型。
 public native boolean isArray() :判斷是否為數組類型。
 public native boolean isPrimitive() :判斷是否為基本類型。
public boolean isAnnotation() :判斷是否為注解類型。
public Package getPackage() :反射中獲得package,如java.lang.Object 的package為java.lang。
public native int getModifiers() : 反射中獲得修飾符,如public static void等 。
public Field getField(String name):反射中獲得域成員。
public Field[] getFields() :獲得域數組成員。    
public Method[] getMethods() :獲得方法。
public Method getDeclaredMethod(String name, Class<?>... parameterTypes):加個Declared代表本類,繼承,父類均不包括。
public Constructor<?>[] getConstructors() :獲得所有的構造函數。

Constructor類

獲取構造器的方法:在Class類中提供的方法;

  • Constructor getConstructor(Class[] params) 根據構造函數的參數,返回一個具體的具有public屬性的構造函數
  • Constructor getConstructors() 返回所有具有public屬性的構造函數數組
  • Constructor getDeclaredConstructor(Class[] params) 根據構造函數的參數,返回一個具體的構造函數(不分public和非public屬性)
  • Constructor getDeclaredConstructors() 返回該類中所有的構造函數數組(不分public和非public屬性)

主要的方法有:

public String getName() :獲取構造器的名字。
public native int getModifiers() : 反射中獲得修飾符,如public static void等 。
getParameterTypes():獲得參數的屬性
newInstance(Object... initargs):使用構造器創建實例

Method類:

和獲取構造器方法相同也有四種方法:

  • Method getMethod(String name, Class[] params) 根據方法名和參數,返回一個具體的具有public屬性的方法
  • Method[] getMethods() 返回所有具有public屬性的方法數組.包括從父類繼承的public方法和實現接口的public方法
  • Method getDeclaredMethod(String name, Class[] params) 根據方法名和參數,返回一個具體的方法(不分public和非public屬性)
  • Method[] getDeclaredMethods() 返回該類中的所有的方法數組(不分public和非public屬性)不包括從父類繼承的方法。

主要的方法有:


public String getName() :獲取構造器的名字。
public native int getModifiers() : 反射中獲得修飾符,如public static void等 。
getParameterTypes():獲得參數的屬性
getReturnType():獲得返回值的屬性
invoke(Object obj, Object... args):第一個參數為該方法的對象,第二個為參數;最重要的方法;

Field類:

獲取Field的方法:在Class類中提供的方法;

  • Field getField(String name) 根據變量名,返回一個具體的具有public屬性的成員變量
  • Field[] getFields() 返回具有public屬性的成員變量的數組
  • Field getDeclaredField(String name) 根據變量名,返回一個成員變量(不分public和非public屬性)
  • Field[] getDelcaredField() 返回所有成員變量組成的數組(不分public和非public屬性)

主要方法有:Field類方法比較多,就不翻譯了,不過完全可以通過名字知道用法

Object    get(Object obj)
Returns the value of the field represented by this Field, on the specified object.
   
boolean    getBoolean(Object obj)
Gets the value of a static or instance boolean field.
   
byte    getByte(Object obj)
Gets the value of a static or instance byte field.
   
char    getChar(Object obj)
Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.
    
Class<?>    getDeclaringClass()
Returns the Class object representing the class or interface that declares the field represented by this Fieldobject.
   
double    getDouble(Object obj)
Gets the value of a static or instance field of type double or of another primitive type convertible to type doublevia a widening conversion.
   
float    getFloat(Object obj)
Gets the value of a static or instance field of type float or of another primitive type convertible to type floatvia a widening conversion.
   
Type    getGenericType()
Returns a Type object that represents the declared type for the field represented by this Field object.
   
int    getInt(Object obj)
Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.
   
long    getLong(Object obj)
Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.
   
int    getModifiers()
Returns the Java language modifiers for the field represented by this Field object, as an integer.
   
String    getName()
Returns the name of the field represented by this Field object.
   
short    getShort(Object obj)
Gets the value of a static or instance field of type short or of another primitive type convertible to type shortvia a widening conversion.
   
Class<?>    getType()
Returns a Class object that identifies the declared type for the field represented by this Field object.
   
boolean    isEnumConstant()
Returns true if this field represents an element of an enumerated type; returns false otherwise.
   
boolean    isSynthetic()
Returns true if this field is a synthetic field; returns false otherwise.
   
void    set(Object obj, Object value)
Sets the field represented by this Field object on the specified object argument to the specified new value.
   
void    setBoolean(Object obj, boolean z)
Sets the value of a field as a boolean on the specified object.
   
void    setByte(Object obj, byte b)
Sets the value of a field as a byte on the specified object.
   
void    setChar(Object obj, char c)
Sets the value of a field as a char on the specified object.
   
void    setDouble(Object obj, double d)
Sets the value of a field as a double on the specified object.
   
void    setFloat(Object obj, float f)
Sets the value of a field as a float on the specified object.
   
void    setInt(Object obj, int i)
Sets the value of a field as an int on the specified object.
   
void    setLong(Object obj, long l)
Sets the value of a field as a long on the specified object.
   
void    setShort(Object obj, short s)
Sets the value of a field as a short on the specified object.
   
String    toGenericString()
Returns a string describing this Field, including its generic type.

簡要演示如下,詳情看注釋:

package net.peace.ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;

public class TestRef {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//Stack<E>
       try {
    	   //裝載指定的類
		Class<Stack> c=(Class<Stack>) Class.forName("java.util.Stack");
		//獲得指定類名的方法;
		Method ms[]=c.getDeclaredMethods();
		//判斷是否屬於特定的類
		System.out.println(c.isInstance(new Stack<>()));
		for(Method m:ms){
			//獲得方法的一些信息;
			System.out.println(m.getModifiers()+" "+m.getReturnType()+" "+m.getName());
			//獲得參數屬性類
			Class[] cc=m.getParameterTypes();
			for(Class p:cc){
				//獲得類名
				System.out.println(p.getName());
			}
			//獲得異常類
			Class[] ce=m.getExceptionTypes();
			for(Class p:ce){
				System.out.println(p.getName());
			}
		}
		System.out.println("******************************");
		//獲得構造器方法
		Constructor<Stack>[] con=(Constructor<Stack>[]) c.getDeclaredConstructors();
		for(Constructor p:con){
			System.out.println(p);
		}
		System.out.println("******************************");
		//獲取域
		Field[] field=c.getDeclaredFields();
		for(Field f:field){
			System.out.println(f);
		}
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
       System.out.println("******************************");
       try {
    	   //通過反射創建不是默認對象的構造器
		Class list=Class.forName("java.util.ArrayList");
		//參數類型設置
	    Class ps[]=new Class[1];
	    ps[0]=Integer.TYPE;
	    //獲得對應參數的構造器
	    Constructor cons=list.getConstructor(ps);
	    //通過調用構造器構建對象
	    Integer[] os={3};	  
	    ArrayList t=( ArrayList)cons.newInstance(os);
	    t.add(1);
	    System.out.println(t.size());
	    //利用反射調用方法
	    //創建參數
	    Class ps3[]= new Class[1];
	    ps3[0]=Object.class;
	    //獲得想要的方法 add
	    Method method1=list.getDeclaredMethod("add", ps3);
	    //進行調用  添加一個元素2;
	    method1.invoke(t, 2);//第一個參數是對象,第二個參數是方法參數;
	  ///調用另外一個構造方法
	    Class ps2[]=new Class[1];
	    ps2[0]=Collection.class;
	    Constructor cons2=list.getConstructor(ps2);
	    ArrayList t2=( ArrayList)cons2.newInstance(t);
	    System.out.println(t2);
	    
	} catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (NoSuchMethodException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InstantiationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IllegalArgumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
       
	}

}

Copyright © Linux教程網 All Rights Reserved