Java Reflection Tutorial for Classes, Methods, Fields, Constructors, Annotations and much more_reports all fields methods 哦日期classes,found in the-程序员宅基地

技术标签: java  Java Reflection  

Reflection in java provides ability to inspect and modify the runtime behavior of applications. Reflection is one of the advance topic of core java. Using reflection we can inspect a class,interfaceenums, get their structure, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values.

  1. Reflection in Java
  2. Reflection for Classes
  3. Reflection for Fields
  4. Reflection for Methods
  5. Reflection for Constructors
  6. Reflection for Annotations

java-reflection-tutorial

Reflection in Java

Reflection is a very powerful concept and it’s of little use in normal programming but it’s the backbone for most of the Java, J2EE frameworks. Some of the frameworks that use reflection are:

  1. JUnit – uses reflection to parse @Test annotation to get the test methods and then invoke it.
  2. Spring – dependency injection, read more at Spring Dependency Injection
  3. Tomcat web container to forward the request to correct module by parsing their web.xml files and request URI.
  4. Eclipse auto completion of method names
  5. Struts
  6. Hibernate

The list is endless and they all use reflection because all these frameworks have no knowledge and access of user defined classes, interfaces, their methods etc.

We should not use reflection in normal programming where we already have access to the classes and interfaces because of following drawbacks.

  • Poor Performance – Since reflection resolve the types dynamically, it involves processing like scanning the classpath to find the class to load, causing slow performance.
  • Security Restrictions – Reflection requires runtime permissions that might not be available for system running under security manager. This can cause you application to fail at runtime because of security manager.
  • Security Issues – Using reflection we can access part of code that we are not supposed to access, for example we can access private fields of a class and change it’s value. This can be a serious security threat and cause your application to behave abnormally.
  • High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t be found at compile time because the classes might not be available, making it less flexible and hard to maintain.

Reflection for Classes

In java, every object is either a primitive type or reference. All the classes, enums, arrays are reference types and inherit from java.lang.Object. Primitive types are – boolean, byte, short, int, long, char, float, and double.

java.lang.Class is the entry point for all the reflection operations. For every type of object, JVMinstantiates an immutable instance of java.lang.Class that provides methods to examine the runtime properties of the object and create new objects, invoke its method and get/set object fields.

In this section, we will look into important methods of Class, for convenience, I am creating some classes and interfaces with inheritance hierarchy.

package com.journaldev.reflection;

public interface BaseInterface {
	
	public int interfaceInt=0;
	
	void method1();
	
	int method2(String str);
}
package com.journaldev.reflection;

public class BaseClass {

	public int baseInt;
	
	private static void method3(){
		System.out.println("Method3");
	}
	
	public int method4(){
		System.out.println("Method4");
		return 0;
	}
	
	public static int method5(){
		System.out.println("Method5");
		return 0;
	}
	
	void method6(){
		System.out.println("Method6");
	}
	
	// inner public class
	public class BaseClassInnerClass{}
		
	//member public enum
	public enum BaseClassMemberEnum{}
}
package com.journaldev.reflection;

@Deprecated
public class ConcreteClass extends BaseClass implements BaseInterface {

	public int publicInt;
	private String privateString="private string";
	protected boolean protectedBoolean;
	Object defaultObject;
	
	public ConcreteClass(int i){
		this.publicInt=i;
	}

	@Override
	public void method1() {
		System.out.println("Method1 impl.");
	}

	@Override
	public int method2(String str) {
		System.out.println("Method2 impl.");
		return 0;
	}
	
	@Override
	public int method4(){
		System.out.println("Method4 overriden.");
		return 0;
	}
	
	public int method5(int i){
		System.out.println("Method4 overriden.");
		return 0;
	}
	
	// inner classes
	public class ConcreteClassPublicClass{}
	private class ConcreteClassPrivateClass{}
	protected class ConcreteClassProtectedClass{}
	class ConcreteClassDefaultClass{}
	
	//member enum
	enum ConcreteClassDefaultEnum{}
	public enum ConcreteClassPublicEnum{}
	
	//member interface
	public interface ConcreteClassPublicInterface{}

}

Let’s look at some of the important refection methods for classes.

Get Class Object

We can get Class of an object using three methods – through static variable class, usinggetClass() method of object and java.lang.Class.forName(String fullyClassifiedClassName). For primitive types and arrays, we can use static variable class. Wrapper classes provide another static variable TYPE to get the class.

		// Get Class using reflection
		Class<?> concreteClass = ConcreteClass.class;
		concreteClass = new ConcreteClass(5).getClass();
		try {
			// below method is used most of the times in frameworks like JUnit
			//Spring dependency injection, Tomcat web container
			//Eclipse auto completion of method names, hibernate, Struts2 etc.
			//because ConcreteClass is not available at compile time
			concreteClass = Class.forName("com.journaldev.reflection.ConcreteClass");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println(concreteClass.getCanonicalName()); // prints com.journaldev.reflection.ConcreteClass
		
		//for primitive types, wrapper classes and arrays
		Class<?> booleanClass = boolean.class;
		System.out.println(booleanClass.getCanonicalName()); // prints boolean
		
		Class<?> cDouble = Double.TYPE;
		System.out.println(cDouble.getCanonicalName()); // prints double
		
		Class<?> cDoubleArray = Class.forName("[D");
		System.out.println(cDoubleArray.getCanonicalName()); //prints double[]
		
		Class<?> twoDStringArray = String[][].class;
		System.out.println(twoDStringArray.getCanonicalName()); // prints java.lang.String[][]

getCanonicalName() returns the canonical name of the underlying class. Notice that java.lang.Class uses Generics, it helps frameworks in making sure that the Class retrieved is subclass of framework Base Class. Check out Java Generics Tutorial to learn about generics and its wildcards.

Get Super Class

getSuperclass() method on a Class object returns the super class of the class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.

		Class<?> superClass = Class.forName("com.journaldev.reflection.ConcreteClass").getSuperclass();
		System.out.println(superClass); // prints "class com.journaldev.reflection.BaseClass"
		System.out.println(Object.class.getSuperclass()); // prints "null"
		System.out.println(String[][].class.getSuperclass());// prints "class java.lang.Object"

Get Public Member Classes

getClasses() method of a Class representation of object returns an array containing Class objects representing all the public classes, interfaces and enums that are members of the class represented by this Class object. This includes public class and interface members inherited from superclasses and public class and interface members declared by the class. This method returns an array of length 0 if this Class object has no public member classes or interfaces or if this Class object represents a primitive type, an array class, or void.

		Class<?>[] classes = concreteClass.getClasses();
		//[class com.journaldev.reflection.ConcreteClass$ConcreteClassPublicClass, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassPublicEnum, 
		//interface com.journaldev.reflection.ConcreteClass$ConcreteClassPublicInterface,
		//class com.journaldev.reflection.BaseClass$BaseClassInnerClass, 
		//class com.journaldev.reflection.BaseClass$BaseClassMemberEnum]
		System.out.println(Arrays.toString(classes));

Get Declared Classes

getDeclaredClasses() method returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object. The returned array doesn’t include classes declared in inherited classes and interfaces.

		//getting all of the classes, interfaces, and enums that are explicitly declared in ConcreteClass
		Class<?>[] explicitClasses = Class.forName("com.journaldev.reflection.ConcreteClass").getDeclaredClasses();
		//prints [class com.journaldev.reflection.ConcreteClass$ConcreteClassDefaultClass, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassDefaultEnum, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassPrivateClass, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassProtectedClass, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassPublicClass, 
		//class com.journaldev.reflection.ConcreteClass$ConcreteClassPublicEnum, 
		//interface com.journaldev.reflection.ConcreteClass$ConcreteClassPublicInterface]
		System.out.println(Arrays.toString(explicitClasses));

Get Declaring Class

getDeclaringClass() method returns the Class object representing the class in which it was declared.

		Class<?> innerClass = Class.forName("com.journaldev.reflection.ConcreteClass$ConcreteClassDefaultClass");
		//prints com.journaldev.reflection.ConcreteClass
		System.out.println(innerClass.getDeclaringClass().getCanonicalName());
		System.out.println(innerClass.getEnclosingClass().getCanonicalName());

Getting Package Name

getPackage() method returns the package for this class. The class loader of this class is used to find the package. We can invoke getName() method of Package to get the name of the package.

		//prints "com.journaldev.reflection"
		System.out.println(Class.forName("com.journaldev.reflection.BaseInterface").getPackage().getName());

Getting Class Modifiers

getModifiers() method returns the int representation of the class modifiers, we can usejava.lang.reflect.Modifier.toString() method to get it in the string format as used in source code.

		System.out.println(Modifier.toString(concreteClass.getModifiers())); //prints "public"
		//prints "public abstract interface"
		System.out.println(Modifier.toString(Class.forName("com.journaldev.reflection.BaseInterface").getModifiers())); 

Get Type Parameters

getTypeParameters() returns the array of TypeVariable if there are any Type parameters associated with the class. The type parameters are returned in the same order as declared.

		//Get Type parameters (generics)
		TypeVariable<?>[] typeParameters = Class.forName("java.util.HashMap").getTypeParameters();
		for(TypeVariable<?> t : typeParameters)
		System.out.print(t.getName()+",");

Get Implemented Interfaces

getGenericInterfaces() method returns the array of interfaces implemented by the class with generic type information. We can also use getInterfaces() to get the class representation of all the implemented interfaces.

		Type[] interfaces = Class.forName("java.util.HashMap").getGenericInterfaces();
		//prints "1"
		System.out.println(Arrays.toString(interfaces));
		//prints "[interface java.util.Map, interface java.lang.Cloneable, interface java.io.Serializable]"
		System.out.println(Arrays.toString(Class.forName("java.util.HashMap").getInterfaces()));
		

Get All Public Methods

getMethods() method returns the array of public methods of the Class including public methods of it’s superclasses and super interfaces.

		Method[] publicMethods = Class.forName("com.journaldev.reflection.ConcreteClass").getMethods();
		//prints public methods of ConcreteClass, BaseClass, Object
		System.out.println(Arrays.toString(publicMethods));

Get All Public Constructors

getConstructors() method returns the list of public constructors of the class reference of object.

		//Get All public constructors
		Constructor<?>[] publicConstructors = Class.forName("com.journaldev.reflection.ConcreteClass").getConstructors();
		//prints public constructors of ConcreteClass
		System.out.println(Arrays.toString(publicConstructors));

Get All Public Fields

getFields() method returns the array of public fields of the class including public fields of it’s super classes and super interfaces.

		//Get All public fields
		Field[] publicFields = Class.forName("com.journaldev.reflection.ConcreteClass").getFields();
		//prints public fields of ConcreteClass, it's superclass and super interfaces
		System.out.println(Arrays.toString(publicFields));

Get All Annotations

getAnnotations() method returns all the annotations for the element, we can use it with class, fields and methods also. Note that only annotations available with reflection are with retention policy of RUNTIME, check out Java Annotations Tutorial.
We will look into this in more details in later sections.

java.lang.annotation.Annotation[] annotations = Class.forName("com.journaldev.reflection.ConcreteClass").getAnnotations();
//prints [@java.lang.Deprecated()]
System.out.println(Arrays.toString(annotations));

Reflection for Fields

Reflection API provides several methods to analyze Class fields and modify their values at runtime, in this section we will look into some of the commonly used reflection functions for methods.

Get Public Field

In last section, we saw how to get the list of all the public fields of a class. Reflection API also provides method to get specific public field of a class through getField() method. This method look for the field in the specified class reference and then in the super interfaces and then in the super classes.

Field field = Class.forName("com.journaldev.reflection.ConcreteClass").getField("interfaceInt");

Above call will return the field from BaseInterface that is implemented by ConcreteClass. If there is no field found then it throws NoSuchFieldException.

Field Declaring Class

We can use getDeclaringClass() of field object to get the class declaring the field.

		try {
			Field field = Class.forName("com.journaldev.reflection.ConcreteClass").getField("interfaceInt");
			Class<?> fieldClass = field.getDeclaringClass();
			System.out.println(fieldClass.getCanonicalName()); //prints com.journaldev.reflection.BaseInterface
		} catch (NoSuchFieldException | SecurityException e) {
			e.printStackTrace();
		}

Get Field Type

getType() method returns the Class object for the declared field type, if field is primitive type, it returns the wrapper class object.

		Field field = Class.forName("com.journaldev.reflection.ConcreteClass").getField("publicInt");
		Class<?> fieldType = field.getType();
		System.out.println(fieldType.getCanonicalName()); //prints int
			

Get/Set Public Field Value

We can get and set the value of a field in an Object using reflection.

			Field field = Class.forName("com.journaldev.reflection.ConcreteClass").getField("publicInt");
			ConcreteClass obj = new ConcreteClass(5);
			System.out.println(field.get(obj)); //prints 5
			field.setInt(obj, 10); //setting field value to 10 in object
			System.out.println(field.get(obj)); //prints 10

get() method return Object, so if field is primitive type, it returns the corresponsing Wrapper Class. If the field is static, we can pass Object as null in get() method.

There are several set*() methods to set Object to the field or set different types of primitive types to the field. We can get the type of field and then invoke correct function to set the field value correctly. If the field is final, the set() methods throw java.lang.IllegalAccessException.

Get/Set Private Field Value

We know that private fields and methods can’t be accessible outside of the class but using reflection we can get/set the private field value by turning off the java access check for field modifiers.

	Field privateField = Class.forName("com.journaldev.reflection.ConcreteClass").getDeclaredField("privateString");
	//turning off access check with below method call
	privateField.setAccessible(true);
	ConcreteClass objTest = new ConcreteClass(1);
	System.out.println(privateField.get(objTest)); // prints "private string"
	privateField.set(objTest, "private string updated");
	System.out.println(privateField.get(objTest)); //prints "private string updated"

Reflection for Methods

Using reflection we can get information about a method and we can invoke it also. In this section, we will learn different ways to get a method, invoke a method and accessing private methods.

Get Public Method

We can use getMethod() to get a public method of class, we need to pass the method name and parameter types of the method. If the method is not found in the class, reflection API looks for the method in superclass.

In below example, I am getting put() method of HashMap using reflection. The example also shows how to get the parameter types, method modifiers and return type of a method.

Method method = Class.forName("java.util.HashMap").getMethod("put", Object.class, Object.class);
//get method parameter types, prints "[class java.lang.Object, class java.lang.Object]"
System.out.println(Arrays.toString(method.getParameterTypes()));
//get method return type, return "class java.lang.Object", class reference for void
System.out.println(method.getReturnType());
//get method modifiers
System.out.println(Modifier.toString(method.getModifiers())); //prints "public"

Invoking Public Method

We can use invoke() method of Method object to invoke a method, in below example code I am invoking put method on HashMap using reflection.

Method method = Class.forName("java.util.HashMap").getMethod("put", Object.class, Object.class);
Map<String, String> hm = new HashMap<>();
method.invoke(hm, "key", "value");
System.out.println(hm); // prints {key=value}

If the method is static, we can pass NULL as object argument.

Invoking Private Methods

We can use getDeclaredMethod() to get the private method and then turn off the access check to invoke it, below example shows how we can invoke method3() of BaseClass that is static and have no parameters.

		//invoking private method
		Method method = Class.forName("com.journaldev.reflection.BaseClass").getDeclaredMethod("method3", null);
		method.setAccessible(true);
		method.invoke(null, null); //prints "Method3"

Reflection for Constructors

Reflection API provides methods to get the constructors of a class to analyze and we can create new instances of class by invoking the constructor. We have already learned how to get all the public constructors.

Get Public Constructor

We can use getConstructor() method on the class representation of object to get specific public constructor. Below example shows how to get the constructor of ConcreteClass defined above and the no-argument constructor of HashMap. It also shows how to get the array of parameter types for the constructor.

		Constructor<?> constructor = Class.forName("com.journaldev.reflection.ConcreteClass").getConstructor(int.class);
		//getting constructor parameters
		System.out.println(Arrays.toString(constructor.getParameterTypes())); // prints "[int]"
		
		Constructor<?> hashMapConstructor = Class.forName("java.util.HashMap").getConstructor(null);
		System.out.println(Arrays.toString(hashMapConstructor.getParameterTypes())); // prints "[]"

Instantiate Object using Constructor

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don’t have the classes information at compile time, we can assign it to Object and then further use reflection to access it’s fields and invoke it’s methods.

		Constructor<?> constructor = Class.forName("com.journaldev.reflection.ConcreteClass").getConstructor(int.class);
		//getting constructor parameters
		System.out.println(Arrays.toString(constructor.getParameterTypes())); // prints "[int]"
		
		Object myObj = constructor.newInstance(10);
		Method myObjMethod = myObj.getClass().getMethod("method1", null);
		myObjMethod.invoke(myObj, null); //prints "Method1 impl."

		Constructor<?> hashMapConstructor = Class.forName("java.util.HashMap").getConstructor(null);
		System.out.println(Arrays.toString(hashMapConstructor.getParameterTypes())); // prints "[]"
		HashMap<String,String> myMap = (HashMap<String,String>) hashMapConstructor.newInstance(null);

Reflection for Annotations

Annotations was introduced in Java 1.5 to provide metadata information of the class, methods or fields and now it’s heavily used in frameworks like Spring and Hibernate. Reflection API was also extended to provide support to analyze the annotations at runtime.

Using reflection API we can analyze annotations whose retention policy is Runtime. I have already written a detailed tutorial on annotations and how we can use reflection API to parse annotations, so I would suggest you to check out Java Annotations Tutorial.

Thats all for reflection in java, I hope you liked the tutorial and understood the importance of Java Reflection API.

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/doctor_who2004/article/details/42196723

智能推荐

级联样式表_级联样式表| 第三部分-程序员宅基地

文章浏览阅读173次。级联样式表 CSS-难以成熟 (CSS — Difficult to maturation)Unlike software, the CSS specifications are developed by successive versions, which would allow a browser to refer to a particular version. CSS was devel..._级联样式表是哪年产生的

sql server学习笔记——批处理语句、存储过程_sql的批处理-程序员宅基地

文章浏览阅读1.7k次。目录批处理语句1、批处理语句简介示例一:示例二:存储过程一、什么是存储过程1、存储过程的简介2、存储过程包含的内容3、存储过程的优点4、存储过程的分类系统存储过程:用户定义存储过程5、常用的系统储存过程(1)一般常用的存储过程(2)xp_cmdshell二、创建存储过程1、定义存储过程的语法2、不带参数的存储过程3、带参数..._sql的批处理

css代码的定位及浮动

上次,我们解除了css的内外边距、鼠标悬停及其练习。现在我们学习css元素练习和定位。

一种简单的蒙特卡洛树搜索并行化方法-程序员宅基地

文章浏览阅读2.2k次,点赞4次,收藏6次。本文提出了 WU-UCT, 一种新颖的并行 MCTS 算法, 通过监控未观察样本的数量来解决并行化过程中统计数据过时的问题. 基于新设计的统计数据, 它有正确地修正了UCT节点选择策略, 实现了有效的探索和利用的权衡. _树搜索并行化

python多页爬取page_python爬虫实现爬取同一个网站的多页数据的实例讲解-程序员宅基地

文章浏览阅读3.2k次。对于一个网站的图片、文字音视频等,如果我们一个个的下载,不仅浪费时间,而且很容易出错。Python爬虫帮助我们获取需要的数据,这个数据是可以快速批量的获取。本文小编带领大家通过python爬虫获取获取总页数并更改url的方法,实现爬取同一个网站的多页数据。一、爬虫的目的从网上获取对你有需要的数据二、爬虫过程1、获取url(网址)。2、发出请求,获得响应。3、提取数据。4、保存数据。三、爬虫功能可以..._python 爬虫 get_page_size

《从0到1学习Flink》—— Flink 读取 Kafka 数据批量写入到 MySQL_flink+kafka统计数据后插入mysql-程序员宅基地

文章浏览阅读2.1k次。本文原创地址是: http://www.54tianzhisheng.cn/2019/01/15/Flink-MySQL-sink/ , 未经允许禁止转载。前言之前其实在 《从0到1学习Flink》—— 如何自定义 Data Sink ? 文章中其实已经写了点将数据写入到 MySQL,但是一些配置化的东西当时是写死的,不能够通用,最近知识星球里有朋友叫我: 写个从 kafka 中读取数据,..._flink+kafka统计数据后插入mysql

随便推点

还在用PPT做组织架构图?公司都在用的架构图软件是什么?_书本里印刷的结构图是用什么软件做的-程序员宅基地

文章浏览阅读3.1k次。还在用PPT、Word和Excel画企业组织结构图吗?对于人力资源的同事来说,画组织结构图是一键非常头疼的事情,尤其是对于一些大公司和人员变动较大的公司来说,需要经常更换组织结构图,每次变动都要耗费大量的时间和精力去重新绘图。其实绘制织结构图很简单,之所以难是因为没有找对工具和方法!今天小编就教你如何用亿图图示轻松绘制一个既美观又专业的组织结构图!下图是一个简单的组织结构图例子,小编就以此为例,详细讲解一下好看清晰、实用的公司组织结构图是怎么画出来的。1、新建组织结构图2、创建组织结构_书本里印刷的结构图是用什么软件做的

ESP32-C3 BLE5.0 扩展蓝牙名称长度的流程_蓝牙广播名称过长-程序员宅基地

文章浏览阅读1.8k次,点赞4次,收藏5次。BLE5.0 扩展蓝牙名称长度_蓝牙广播名称过长

centos8安装NVIDIA显卡驱动,docker模式运行机器学习_centos8安装显卡驱动-程序员宅基地

文章浏览阅读3.5k次。centos8安装NVIDIA显卡驱动,docker模式运行机器学习_centos8安装显卡驱动

利用优先级拥抱需求变更_需求优先级反复变化-程序员宅基地

文章浏览阅读2.4k次。需求变更这件事,每个开发人员都遇到过,每个产品经理也都遇到过。 以前,我们会追求需求不变更,但无论是产品型团队还是项目型团队,需求不变更都是天方夜谈,不可能实现的。即使把需求变更的成本提得很高,流程搞得很复杂,又要填变更单,又要几级经理审批,又要需求评审,依然无法避免。 于是,团队的目标变成了少变更,希望尽量少的变更既能满足业务的需要,又能减少开发团队的反感。但‘少’是个相对的概念_需求优先级反复变化

素数筛法_筛法求素数-程序员宅基地

文章浏览阅读2.3k次。一,素数筛法如果需要用到素数表,要么硬编码,要么自己求出前若干项素数。硬编码适合小表,大表只能自己求,而最常见的就是筛法。_筛法求素数

【深度长文】细思极恐的YouTube可跳过广告-程序员宅基地

文章浏览阅读1.8k次。【预警】:Youtube的可跳过广告尽管极其精妙(看完你就知道了),但其实并没有到细思极恐的程度;同时本文也并非深度长文,长是比较长,深不深度就另说了!作为一个广告PM,这种标题党行为都是为了优化点击率。开篇就明确文章属标题党,如今像我这样的良心作者已经不多了,快猛戳关注啊!有一些互联网产品:你认为它很简单、甚至很愚蠢,然而实际上它的设计却无比精妙、细思极恐,YouTube的5秒可跳过的贴片广

推荐文章

热门文章

相关标签