Java反射机制

1.概念

JAVA反射机制主要提供如下功能:html

一、在运行时判断任意一个对象所属的类java

二、在运行时构造任意一个类的对象api

三、在运行时判断任意一个类所具备的成员变量和方法(经过反射甚至能够调用private方法)数组

四、在运行时调用任意一个对象的方法(******注意:前提都是在运行时,而不是在编译时)oracle

2. Class对象

Class对象是Java反射的基础,它包含了与类相关的信息,事实上,Class对象就是用来建立类的全部对象的。Class对象是java.lang.Class<T>这个类生成的对象,其中类型参数T表示由此 Class 对象建模的类的类型。例如,String.class的类型是 Class<String>;若是将被建模的类未知,则使用Class<?>.ide

Class没有公共构造方法。Class对象是在加载类时由Java虚拟机以及经过调用类加载器中的defineClass方法自动构造的。函数

获取Class对象的几种方法:学习

  1. 经过实例变量的getClass()方法:Object类中的方法,每一个类都拥有此方法
    1. Class<?> getClass()

      Returns the runtime class of this Object.this

    2. 实例:
      Class c1 = new String("abc").getClass();

       

  2. 经过Class类的静态方法 forName(className)
    1. 经过位于java.lang.Class<T>的forName静态方法
      1.     
        static Class<?> forName(String className)

        Returns the Class object associated with the class or interface with the given string name.
        (返回与给定字符串名称的类或接口相关联的Class对象.className彻底限定类名-类名要包括全部包)spa

        static Class<?> forName(String name, boolean initialize, ClassLoader loader)

        Returns the Class object associated with the class or interface with the given string name, using the given class loader.
        (使用给定的类加载器返回与给定字符串名称的类或接口相关联的Class对象。)

      2. 示例
        1. Class class=Class.forName("com.chuyu.util.Myreflect");//参数即为类的完整包名

           

  3. 使用类字面常量或TYPE字段
    1. Class MyreflectClass=Myreflect.class;//(类字面常量不只能够应用于普通的类,也能够应用于接口、数组以及基本数据类型)
      Class c = Integer.TYPE;//(TYPE是基本数据类型的包装类型的一个标准字段,它是一个引用,指向对应的基本数据类型的Class对象)

      附表:    

3.java.lang.reflect 经常使用API
(参考http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-summary.html)

Class Summary 

Class Description
AccessibleObject

The AccessibleObject class is the base class for Field, Method and Constructor objects.
(AccessibleObject类是Field,Method和Constructor对象的基类.)

Array

The Array class provides static methods to dynamically create and access Java arrays.
(Array类提供静态方法来动态建立和访问Java数组。)

Constructor<T>

Constructor provides information about, and access to, a single constructor for a class.
(构造函数提供有关类的单个构造函数的信息和访问权限。)

Field

A Field provides information about, and dynamic access to, a single field of a class or an interface.
(提供有关类或接口的单个​​字段的信息和动态访问。)

Method

A Method provides information about, and access to, a single method on a class or interface.
(方法提供有关类和接口上单个方法的信息和访问.)

Modifier

The Modifier class provides static methods and constants to decode class and member access modifiers.
(Modifier类提供静态方法和常量来解码类和成员访问修饰符。)

Proxy

Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
(代理类提供静态方法来建立动态代理类和实例,它也是由这些方法建立的全部动态代理类的超类.)

ReflectPermission

The Permission class for reflective operations.
(反射操做的权限类)

4.经常使用Api详解;

        4.1 Constructor<T>类

从Class对象获取Constructor类的方法

Modifier and Type Method and Description
Constructor<T> getConstructor(Class<?>... parameterTypes)

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.
(返回一个Constructor对象,该对象反映由此Class对象表示的类的指定的公共构造函数。)

Constructor<?>[] getConstructors()

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.
(返回一个Constructor对象,该对象反映由此Class对象表示的类或接口的指定构造函数。)

Constructor<?>[] <getDeclaredConstructors()

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.
(返回一个Constructor对象数组,反映由此Class对象表示的类声明的全部构造函数。)

 

4.1.2 :Constructor类中经常使用的方法:

Method Summary 

Modifier and Type Method and Description
String getName()

Returns the name of this constructor, as a string.

Class<?>[] getParameterTypes()

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object.

T newInstance(Object... initargs)

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

String toGenericString()

Returns a string describing this Constructor, including type parameters.

String toString()

Returns a string describing this Constructor.

        示例:

(1) 获取Constructor对象

(2) 构造函数参数

(3) 使用Constructor对象实例化对象

package com.chuyu.it.utils;

import java.lang.reflect.Constructor;

public class Student {
    public String name;
    public String sex;
    private  String age;
    //省略set/get 方法
    public Student(String name, String sex, String age) {
        super();
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    public Student() {
        super();
    }
    public static void main(String[] args) throws Exception{
        Class<?> clz=Student.class;
        Constructor<?>  constructors= clz.getConstructor(new Class[]{String.class,String.class,String.class});
        Student stu=(Student) constructors.newInstance("张三","男","22");//newInstance(Object... initargs)建立实例
        System.out.println(constructors.getName());//com.chuyu.it.utils.Student
        Class<?>[]  paramsArray=constructors.getParameterTypes();
        for (Class<?> class1 : paramsArray) {
            System.out.println(class1.getName());//java.lang.String java.lang.String java.lang.String
        }
        System.out.println(constructors.toGenericString());//public com.chuyu.it.utils.Student(java.lang.String,java.lang.String,java.lang.String)
        System.out.println(constructors.toString());//public com.chuyu.it.utils.Student(java.lang.String,java.lang.String,java.lang.String)
    }
}

                    

4.2:Method类

        4.2.1 java.lang.Class<?>对象获取Method对象的方法        

Method getDeclaredMethod(String name, Class<?>... parameterTypes)

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
(返回一个Method对象,该对象反映由此Class对象表示的类或接口的指定声明方法。)

Method[] getDeclaredMethods()

Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object.

Method getMethod(String name, Class<?>... parameterTypes)

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.    

        获取到Method类后调用

public Class<?>[] getParameterTypes() //获取参数类型
public String getName()//获取方法名
public Class<?> getReturnType()//获取返回类型
public Object invoke(Object obj,
            Object... args) //obj实例对象调用该方法,args 方法的入参

示例:

public class Student {

...//同上

private static void sayHello(String name){
        System.out.println("Hello:"+name);
    }

    public static void main(String[] args) throws Exception{
        Class<?> clz=Student.class;
        Constructor<?>  constructors= clz.getConstructor(new Class[]{String.class,String.class,String.class});
        Student stu=(Student) constructors.newInstance("张三","男","22");//newInstance(Object... initargs)
        
        //public Method getDeclaredMethod(String name,Class<?>... parameterTypes)
        Method sayHelloMethod=clz.getDeclaredMethod("sayHello", new Class[]{String.class});
        //invoke(Object obj, Object... args)
        sayHelloMethod.invoke(stu,stu.name);//Hello:张三
    }
}

4.4Field类

一样的,也是经过java.lang.Class<?>类中的方法获取反射类的Field类

public Field getDeclaredField(String name)//获取声明的指定字段
public Field[] getDeclaredField()//获取全部声明的字段
public Field getField(String name)//获取指定声明的公告字段
public Field[] getField()//获取全部可访问的公共字段

在获取到Field类后的方法(参见:http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html) ,调用相应的方法.

public Object get(Object obj)//获取字段的值
public void set(Object obj,Object value)//设置字段的值
getType/getName以及一些基本数据类型的getXxxx(Object obj)和setXxxx(Object obj,Xxxx value) //Xxxx 表示基本数据类型的包装类

 

示例:

package com.chuyu.it.utils;

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

public class Student {
  
        ...//同上

    public static void main(String[] args) throws Exception{
        Class<?> clz=Student.class;
        Constructor<?>  constructors= clz.getConstructor(new Class[]{});//调用无参构造方法
        Student stu=(Student) constructors.newInstance();//newInstance(Object... initargs)
        Field [] fields=clz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getType().getName());//java.lang.String
        }
        Field fieldforName=clz.getDeclaredField("name");
        fieldforName.set(stu, "zhangsan");
        System.out.println(fieldforName.get(stu));//zhangsan
    }
}

 

总结:  其中对于Construct<?>,Method,Field 类都有getDeclaredXxxxxx(参数列表),以及无参的getDeclaredXxxxxx 表示的 都是获取声明的全部(包含private 修饰的私有)的构造方法类,方法类,字段类.而

getXxxxx则表示只获取公共的构造方法类,方法类,字段类.

整个java反射Api大体以下:

                java反射机制

--------------------------------分割线----------------------------------------------------

以上只是做为我的学习的初始知识整理,后续在工做中实际遇到的再作整理

                                                                       2017年4月7日14:06:06

相关文章
相关标签/搜索