Basic Concepts
The Java reflection mechanism allows us to check the information of classes, interfaces, variables, and methods at run time (runtime) outside of the compile period (Compile time) .
With reflection, all the properties and methods of the class can be known for any one class, and any one of its methods and properties can be called for any object.
Class
To get the information for a class, you first need to get the class object of the classes.
All types in Java include the base type (int, long, float, and so on), even if the array has an object of the class class associated with it.
Gets the object of the class
//在编译期知道一个类的名字//在程序运行的时候获取类名(需要包括完整的包名) Cllss clas = Class.forName("com.test.Demo")
Get class Name
//获取简单类名String className = cls.getName();//获取完整类型(包括包名)String simpleClassName =cls.getSimpleName();
Get modifier
Class cls =Demo.class;// 修饰符都被包装成一个int类型的数字,这样每个修饰符都是一个位标识(flag bit) int modifiers = cls.getModifiers();// 判断修饰符类型Modifier.isPublic( modifiers);Modifier.isProtected( modifiers);Modifier.isPrivate( modifiers);Modifier.isAbstract( modifiers);Modifier.isInterface( modifiers);Modifier.isFinal( modifiers);Modifier.isStatic( modifiers);Modifier.isNative( modifiers);Modifier.isStrict( modifiers);Modifier.isSynchronized( modifiers);Modifier.isTransient( modifiers);Modifier.isVolatile( modifiers);
Get package information
Class cls =Demo.class;Package p = cls.getPackage();
Gets the inherited parent class
Class cls =Demo.class;//superclass 对象其实就是一个Class类的实例,可以继续在这个对象上进行反射操作Class superClass = cls.getSuperclass();
Access to the implemented interface
Class cls = Demo.class;//由于一个类可以实现多个接口,所有返回的是接口数组,同样的接口中也有 Class 对象Class [ ] interfaces = cls.getInterfaces();
Constructor
1. Get the constructor method
Get all the public constructor methods
Class Demo {demo () {} Public Demo(String str) {} Public Demo(String str,intnum) {}} Public class Test { Public Static void Main(string[] args) {Class CLS = Demo.class; Constructor[] Constructors = cls.getconstructors (); for(Constructor constructor:constructors) {System.out.println (constructor); } }}//Output Result://Public Demo (java.lang.String)//Public Demo (Java.lang.string,int)
Gets the specified public constructor method
//...省略 Demo 类Class cls = Demo.class// 若不存在匹配的公共构造函数,抛出 java.lang.NoSuchMethodException 异常Constructor constructor = cls.getConstructor(new Class[]{String.class,int.class});
2. Get constructor Method parameters
Constructor constructor = ...//只提供获取所有构造参数的方法,没有获取指定参数的方法Class [] paramterTypes = constructor.getParameterTypes();
3. Instantiating a class with a constructor function
Class cls = ...Constructor constructor = cls.getConstructor(new Class[]{String.class});// newInstance 里面的参数,需要与构造函数的参数精确匹配才能生效// 例如下面的例子中构造函数参数是 String,则在实例化类就必须提供一个 String 的对象(即 "demo")Demo demo = (Demo) constructor.newInstance(new Object[]{"demo"});
Field
1. Get Variables
Get all variables (public, non-public)
Class Demo {BooleanIsTrue;PrivateString str; Public intNum } Public class Test { Public Static void Main(string[] args)throwsException {Class cls = Demo.class; field[] fields = Cls.getfields (); Field [] privatefields =cls.getdeclaredfields (); for(Field field:fields) {System.out.println ("Public parameters:"+field); } for(Field privatefield:privatefields) {System.out.println ("Non-public parameter:"+privatefield); } }}//Output Result://Common parameters: public int demo.num//non-public parameters: Boolean demo.istrue//non-public parameters: private java.lang.String demo.str//non-common parameters: public int demo.num
Gets the specified variable (public, non-public)
//...省略相同代码Class cls = Demo.class;//名称不匹配,抛出 java.lang.NoSuchFieldException 异常Field field = cls.getField("num");Field privateField = cls.getDeclaredField("str");
2.
get/Set Variable value
Class<?> cls = Demo.class;Demo demo = (Demo) cls.newInstance();// setterField field = cls.getField("num"1000);//getterint filedValue = (Integer) field.get(demo);// setterField privateField = cls.getDeclaredField("str");// 关键 --> 设置访问权限privateField.setAccessible(true"hello");//getterString privateFieldValue = (String) privateField.get(demo);// 输出结果System.out.println(filedValue);System.out.println(privateFieldValue);
Method
1. Get Method Objects
Get all methods
class Demo { public String print(String str) { return str; } privatevoidsay(){ }}publicclass Test { publicstaticvoidmainthrows Exception { Class cls = Demo.class; // 包括从父类继承而来的 Method[] methods = cls.getMethods(); Method [] privateMethods = cls.getDeclaredMethods(); }}
Gets the specified method
//...省略相同方法Class cls = Demo.class;//getMethod(方法名,方法参数类型)Method method = cls.getMethod("print"new Class[]{String.class});Method privateMethod = cls.getMethod("say"null);
2. Get method parameter Types
Method method = ...//获取所有的参数类型Class [] paramterTypes = method.getParameterTypes();//获取返回类型Class reeturnType = method.getReturnType();
3. Calling Methods
Class cls = Demo.class;Demo demo = (Demo) cls.newInstance();Method method = cls.getMethod("print"new Class[]{String.class});//调用公用方法(类实例,方法的参数的具体值)"hello");//调用私有方法Method privateMethod = cls.getDeclaredMethod("print"new Class[]{String.class});// 关键-->获得访问权限privateMethod.setAccessible(true"hello");
4. Judging the Getter/setter method
Public Static Boolean Isgetter(method) {if(!method.getname (). StartsWith ("Get")){return false; }if(Method.getparametertypes (). length! =0){return false; }if(void. Class.equals (Method.getreturntype ())) {return false; }return true;} Public Static Boolean Issetter(method) {if(!method.getname (). StartsWith ("Set")){return false; }if(Method.getparametertypes (). length! =1){return false; }return true;}
Array
PackageCom.controller;ImportJava.lang.reflect.Array; Public class Test{ Public Static void Main(string[] args)throwsclassnotfoundexception {//Create a data int[] Intarray = (int[]) Array.newinstance (int. class,3);//Access an arrayArray.set (Intarray,0, -); Array.set (Intarray,1, $); System.out.println ("intarray[0] ="+ Array.get (Intarray,0)); System.out.println ("intarray[1] ="+ Array.get (Intarray,1));//Get the Class object of the arrayClass stringarrayclass = String[].class;//In the JVM the letter I represents the int type, the left ' [' means I want an array of type intClass Intarrayclass = Class.forName ("[I");//Note that the right side of ' [L ' is the class name, and the right side of the class name is a '; ' Symbol. The meaning of this is an array of the specified type. Stringarrayclass = Class.forName ("[Ljava.lang.String;]);//Gets the member type of the arrayString [] strings =Newstring[3]; Class Stringsarrayclass = Strings.getclass (); Class Stringsarraycomponenttype =stringsarrayclass.getcomponenttype (); System.out.println (Stringsarrayclass); }}
Java Basics-Reflection