Java反射机制--Class,Field,Method,Constructor

参考文章:深入理解java反射

在java核心卷1中对反射的定义:能够分析类的能力的程序称之为反射。
反射的功能极其强大,反射机制可以用来:
    1.在运行中分析类的能力。
    2.在运行中查看对象,例如编写一个toString方法 //后续博客我会把这个方法记录出来
    3.实现通用的数组操作代码。
    4.利用Method对象。

java反射的作用简单来说就是在编译时,不需要知道具体的那个类,而是在运行的时候知道时那个类并调用该类的方法.

java反射的核心就是获取Class对象,通过这个class对象我们就可以获取到加载到虚拟机当中这个Class对象对应的方法、成员以及构造方法的声明和定义等信息。

获取Class的方法有三种:

Student st = new Student();
Class c = st.getClass();
Class c = Student.class;
Class c = Class.forName("package.Student");
Class对象的一些常用方法

c.isAssignableFrom(Class clz) //用来判断一个类Class1和另一个类Class2是否相同或是另一个类的超类或接口。
c.getName()                   //获取当前类名称
c.newInstance()               //创建当前类的一个新实例,默认调用无参的构造函数
c.getClassloader()            //返回该类的类加载器
c.getComponentType()          //返回数组组件类型的Class,若不是数组,返回空
c.getSupperclass()            //返回当前类的超类
c.isArray()                   //判断是否是数组对象

java虚拟机为每个类型管理一个Class对象,因此可以使用==运算符进行比较
if(st.getClass == Student.class)
在java.lang.reflect包中有三个类Field,Method,Constructor分别用于描述类的属性,方法和构造器

Class类提供了四种方法访问Field,Method,Constructor

Field f = c.getField("fieldname") //根据传入的String内容返回对应的属性,但是只对public声明的属性有效
//根据String method,Class...class 获取相应的方法,但是只对public声明的方法有效
Method m =c.getMethod("methodname",new Class[]{int.class,int.class,int.class});
Constructor co = c.getConstructor(parameterTypes...); //根据对应的传入参数返回public构造器


Field[] f = c.getFields() // 获取当前类的public属性
Method[] m =c.getMethods()//获取当前类的public方法
Constructor[] co = c.getConstructor() // 获取当前类的public构造器


//下面所说的不包括超类,指的是只获取在当前类中声明的属性,方法和构造器(public和private等都可以)
//但是并不能获取在超类中定义的任何属性,方法和构造器
Field[] f = c.getDeclaredFields(); //获取当前类的所有属性,包括私有和共有的,但是不包括超类
Method[] m = c.getDeclaredMethods();//获取当前类的所有方法,包括私有和共有的,但是不包括超类
Constructor[] co = c.getDeclaredConstructors();//获取当前类的所有属性,包括私有和共有的,但是不包括超类


Field[] f = c.getDeclaredField("FieldName"); //获取指定属性名称的类属性,但是不包括超类
Method[] m = c.getDeclaredMethod("MethodName",parameterTypes);//获取指定方法名的类方法,但是不包括超类
Constructor[] co = c.getDeclaredConstructor(parameterTypes);//获取指定参数的当前类的构造器,但是不包括超类

以上介绍了如何获取了Field,Method,Constructor, 下面介绍下这三个类的一些常用方法

//java.lang.reflect.Field
Modifier.toString(field.getModifiers()) //以整数形式返回由此 Field 对象表示的字段的 Java 语言修饰符
field.getType() //返回一个class,表示该字段的声明类型
field.get(obj) //返回指定对象field字段上对应的值
field.set(obj,55)//设置指定对象上field字段的值


//java.lang.reflect.Method
Modifier.toString(addMethod.getModifiers())); //一下四个函数分别获取 Method 的修饰符,返回值,函数名称,函数参数列表
Method.getReturnType());
Method.getName());
Method.getParameterTypes());

Method.invoke(obj,Parameterlist) //对指定函数调用Method方法,parameterlist为参数列表


//java.lang.reflect.Constructor
Modifier.toString(constructor.getModifiers()) //一下三个函数分别获取 Constructor的修饰符,函数名称,函数参数列表
constructor.getName()
constructor.getParameterTypes()

constructor2.newInstance(new Object[]{33,"haha"})//调用带参数构造器生成类实例
下面是《java核心编程1》作者编写的一段简单的reflecttest代码,可以作为参考

输出了类的所有构造器,方法和属性

package reflection;

import java.util.*;
import java.lang.reflect.*;

/**
 * This program uses reflection to print all features of a class.
 * @version 1.1 2004-02-21
 * @author Cay Horstmann
 */
public class ReflectionTest
{
   public static void main(String[] args)
   {
      // read class name from command line args or user input
      String name;
      if (args.length > 0) name = args[0];
      else
      {
         Scanner in = new Scanner(System.in);
         System.out.println("Enter class name (e.g. java.util.Date): ");
         name = in.next();
      }

      try
      {
         // print class name and superclass name (if != Object)
         Class cl = Class.forName(name);
         Class supercl = cl.getSuperclass();
         String modifiers = Modifier.toString(cl.getModifiers());
         if (modifiers.length() > 0) System.out.print(modifiers + " ");
         System.out.print("class " + name);
         if (supercl != null && supercl != Object.class) System.out.print(" extends "
               + supercl.getName());

         System.out.print("\n{\n");
         printConstructors(cl);
         System.out.println();
         printMethods(cl);
         System.out.println();
         printFields(cl);
         System.out.println("}");
      }
      catch (ClassNotFoundException e)
      {
         e.printStackTrace();
      }
      System.exit(0);
   }

   /**
    * Prints all constructors of a class
    * @param cl a class
    */
   public static void printConstructors(Class cl)
   {
      Constructor[] constructors = cl.getDeclaredConstructors();

      for (Constructor c : constructors)
      {
         String name = c.getName();
         System.out.print("   ");
         String modifiers = Modifier.toString(c.getModifiers());
         if (modifiers.length() > 0) System.out.print(modifiers + " ");         
         System.out.print(name + "(");

         // print parameter types
         Class[] paramTypes = c.getParameterTypes();
         for (int j = 0; j < paramTypes.length; j++)
         {
            if (j > 0) System.out.print(", ");
            System.out.print(paramTypes[j].getName());
         }
         System.out.println(");");
      }
   }

   /**
    * Prints all methods of a class
    * @param cl a class
    */
   public static void printMethods(Class cl)
   {
      Method[] methods = cl.getDeclaredMethods();

      for (Method m : methods)
      {
         Class retType = m.getReturnType();
         String name = m.getName();

         System.out.print("   ");
         // print modifiers, return type and method name
         String modifiers = Modifier.toString(m.getModifiers());
         if (modifiers.length() > 0) System.out.print(modifiers + " ");         
         System.out.print(retType.getName() + " " + name + "(");

         // print parameter types
         Class[] paramTypes = m.getParameterTypes();
         for (int j = 0; j < paramTypes.length; j++)
         {
            if (j > 0) System.out.print(", ");
            System.out.print(paramTypes[j].getName());
         }
         System.out.println(");");
      }
   }

   /**
    * Prints all fields of a class
    * @param cl a class
    */
   public static void printFields(Class cl)
   {
      Field[] fields = cl.getDeclaredFields();

      for (Field f : fields)
      {
         Class type = f.getType();
         String name = f.getName();
         System.out.print("   ");
         String modifiers = Modifier.toString(f.getModifiers());
         if (modifiers.length() > 0) System.out.print(modifiers + " ");         
         System.out.println(type.getName() + " " + name + ";");
      }
   }
}











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值