Java如何通过反射获取类的属性与方法

 更新时间:2026年08月15日 08:47:51   作者:Fy哥  
还在为Java反射获取属性和方法而困惑吗?本文详细讲解Class类实例获取、getFields与getDeclaredFields的区别、权限修饰符、变量类型、方法注解等核心知识点,并附有代码示例,帮助你快速掌握反射机制

1.获取Class类的实例

2.获取属性

2.1 获取声明为public的属性

Field[]  fields  = clazz.getFields();

上述代码只能够获取声明为public的属性

代码演示:

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

import org.junit.Test;

public class TestConstructor {

	@Test
	public void test1() throws Exception {
		
		String str = new String("exer03.Person");
		
		@SuppressWarnings("unchecked")
		Class<Person> clazz = (Class<Person>) Class.forName(str);
		
		//获取运行时类的属性
		Field[]  fields  = clazz.getFields();
		for(int i = 0;i < fields.length;i++) {
			System.out.println(fields[i]);//打印输出
		}
		
	}
}

在Person类中,声明的属性有name、age

 而通过Field[]  fields  = clazz.getFields(); 获取的属性,结果如下:

2.1.1 如果将Person类的属性的修饰符设定为非public

 通过Field[]  fields  = clazz.getFields(); 获取的属性,结果如下:

 通过上述讲解,可以知道Field[]  fields  = clazz.getFields(); 获取的属性的修饰符为public

2.1.2 获取父类的public的属性

父类Creature

public class Creature {

	public boolean flag;
	
}

子类Person 

2.2 获取声明的属性

只要在类中声明的属性,都可以通过反射获取到

Field[]  fields  = clazz.getDeclaredFields();

 代码演示:

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

import org.junit.Test;

public class TestConstructor {

	@Test
	public void test1() throws Exception {
		
		String str = new String("exer03.Person");
		
		@SuppressWarnings("unchecked")
		Class<Person> clazz = (Class<Person>) Class.forName(str);
		
		//获取运行时类的属性
		Field[]  fields  = clazz.getDeclaredFields();
		for(Field field : fields) {
			System.out.println(field);
		}
		
	}
}

在Person类中,声明的属性有name、age、sex、address

  而通过Field[]  fields  = clazz.getDeclaredFields(); 获取的属性,结果如下:

2.3 getDeclaredFields()与getFields()区别

  1. getDeclaredFields() 只可以访问本类当中的属性
  2. getFields()只能访问声明为public的属性
  3. getDeclaredFields() 可以访问声明为任意权限修饰符的属性
  4. getFields() 可以访问父类中的声明为public的属性

2.4 通过属性获取权限修饰符、变量类型和变量名

2.4.1 获取权限修饰符

int i = field.getModifiers();//返回值为int型

返回类型说明:

  • 权限修饰符为default       返回值0
  • 权限修饰符为public         返回值1
  • 权限修饰符为private       返回值2
  • 权限修饰符为protected   返回值4

 

使用Modifier.toString(int i) 以字符串形式打印出来

String str1 = Modifier.toString(i);//i 是指 0 1 2 4等

 代码示例:

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

import org.junit.Test;

public class TestConstructor {

	@Test
	public void test1() throws Exception {
		
		String str = new String("exer03.Person");
		
		@SuppressWarnings("unchecked")
		Class<Person> clazz = (Class<Person>) Class.forName(str);
		
		//获取运行时类的属性
		Field[]  fields  = clazz.getDeclaredFields();
		for(Field field : fields) {
			
			//1.获取属性的权限修饰符
			int i = field.getModifiers();//返回值为int型
			String str1 = Modifier.toString(i);
			System.out.print(i + " ");
			

		}
		
	}
}

结果截图:

2.4.2 获取变量类型

Class c =  field.getType();//返回值类型:Class

代码示例:

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

import org.junit.Test;

public class TestConstructor {

	@Test
	public void test1() throws Exception {
		
		String str = new String("exer03.Person");
		
		@SuppressWarnings("unchecked")
		Class<Person> clazz = (Class<Person>) Class.forName(str);
		
		//获取运行时类的属性
		Field[]  fields  = clazz.getDeclaredFields();
		for(Field field : fields) {
			
			//1.获取属性的权限修饰符
//			int i = field.getModifiers();//返回值为int型
//			String str1 = Modifier.toString(i);
//			System.out.print(str1 + " ");
			
			//2.获取属性的变量类型
			Class c =  field.getType();
			System.out.print(c.getName() + " ");
			
			System.out.println();
		}
		
	}
}

结果截图:

2.4.3 获取变量名

System.out.println(field.getName());

代码演示:

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

import org.junit.Test;

public class TestConstructor {

	@Test
	public void test1() throws Exception {
		
		String str = new String("exer03.Person");
		
		@SuppressWarnings("unchecked")
		Class<Person> clazz = (Class<Person>) Class.forName(str);
		
		//获取运行时类的属性
		Field[]  fields  = clazz.getDeclaredFields();
		for(Field field : fields) {
			
			//1.获取属性的权限修饰符
			int i = field.getModifiers();//返回值为int型
			String str1 = Modifier.toString(i);
			System.out.print(str1 + " ");
			
			//2.获取属性的变量类型
			Class c =  field.getType();
			System.out.print(c.getName() + " ");
			
			//3.获取属性的变量名
			System.out.println(field.getName());
			
			System.out.println();
		}
		
	}
}

效果截图:

3.获取方法

3.1getMethods()和getDeclaredMethods()

获取方法与获取属性相似!同样具有两种方法

  1. Method[] methods =  clazz.getMethods();
  2. Method[] methods2 =  clazz.getDeclaredMethods();
import java.lang.reflect.Method;

import org.junit.Test;

public class TestMethon {

	@Test
	public void test1() {
		
		Class<Person> clazz = Person.class;
		
		//getMethods():获取运行时类及其父类的声明为public的方法
		Method[] methods =  clazz.getMethods();
		for(Method method : methods) {
			System.out.println(method);
		}
		
		//getDeclaredMethods() : 获取运行时类的所有方法
		Method[] methods2 =  clazz.getDeclaredMethods();
		for(Method method : methods2) {
			System.out.println(method);
		}
		
	}
	
}

结果截图:

Method[] methods =  clazz.getMethods();得到的结果

Method[] methods2 =  clazz.getDeclaredMethods();得到的结果

方法的主要构成
1注解
2权限修饰符
3返回值类型
4方法名
5形参列表
6异常

3.2 获取注解

Annotation[] annotation =  method.getAnnotations();

3.2.1 如何创建注解?

要想获取注解,就一定要有注解!

代码示例:(自定义注解)

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

	String[] value();
}

3.2.2 使用自定义注解

代码示例:

在一个类中的方法上,添加注解

@MyAnnotation(value = "I am Person")
public void show() {
	System.out.println("我是Person类");
}

3.2.3 获取注解

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import org.junit.Test;

public class TestMethon {
	
	@Test 
	public void test2() {
		
		Class<Person> clazz = Person.class;
		
		Method[] methods =  clazz.getDeclaredMethods();
		for(Method method : methods) {
			
			//1.获取注解
			Annotation[] annotation =  method.getAnnotations();
			for(Annotation a : annotation) {
				System.out.println(a);
			}
			
			//获取方法名
			System.out.print(method.getName() + "  ");
			
			System.out.println();
			
		}
		
	}
}

结果截图:

3.3 获取权限修饰符

获取权限修饰符,与前面获取属性的权限修饰符一样。

int i = method.getModifiers();

代码演示:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;

public class TestMethon {
	
	@Test 
	public void test2() {
		
		Class<Person> clazz = Person.class;
		
		Method[] methods =  clazz.getDeclaredMethods();
		for(Method method : methods) {
			
			//1.获取注解
			Annotation[] annotation =  method.getAnnotations();
			for(Annotation a : annotation) {
				System.out.println(a);
			}
			
			//2.获取权限修饰符
			int i = method.getModifiers();
			String str = Modifier.toString(i);
			System.out.print(str + " ");
			
			//获取方法名
			System.out.print(method.getName() + " ");
			
			System.out.println();
			
		}
		
	}
}

效果截图:

3.4 获取返回值类型

Class returnType = method.getReturnType();

代码示例:

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;

public class TestMethon {
	
	@Test 
	public void test2() {
		
		Class<Person> clazz = Person.class;
		
		Method[] methods =  clazz.getDeclaredMethods();
		for(Method method : methods) {
			
			//1.获取注解
			Annotation[] annotation =  method.getAnnotations();
			for(Annotation a : annotation) {
				System.out.println(a);
			}
			
			//2.获取权限修饰符
			int i = method.getModifiers();
			String str = Modifier.toString(i);
			System.out.print(str + " ");
			
			//3.获取返回类型
			Class returnType = method.getReturnType();
			System.out.print(returnType.getName() + " ");
			
			//获取方法名
			System.out.print(method.getName() + " ");
			
			System.out.println();
			
		}
	}
}

效果截图:

3.5  获取方法名

System.out.print(method.getName() + " ");

3.6 获取参数列表

Class[] param =  method.getParameterTypes();

打印输出参数列表

Class[] param =  method.getParameterTypes();
System.out.print("(");
for(int j = 0;j < param.length;j++) {	
    if(j == param.length - 1) {
	    System.out.print(param[j].getName() + " args-" + j);
    }else {
		System.out.print(param[j].getName() + " args-" + j + ",");
	}
}
System.out.print(")");

代码示例

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;

public class TestMethon {
	
	@Test 
	public void test2() {
		
		Class<Person> clazz = Person.class;
		
		Method[] methods =  clazz.getDeclaredMethods();
		for(Method method : methods) {
			
			//1.获取注解
			Annotation[] annotation =  method.getAnnotations();
			for(Annotation a : annotation) {
				System.out.println(a);
			}
			
			//2.获取权限修饰符
			int i = method.getModifiers();
			String str = Modifier.toString(i);
			System.out.print(str + " ");
			
			//3.获取返回类型
			Class returnType = method.getReturnType();
			System.out.print(returnType.getName() + " ");
			
			//4.获取方法名
			System.out.print(method.getName() + " ");
			
			//5.获取参数列表
			Class[] param =  method.getParameterTypes();
			System.out.print("(");
			for(int j = 0;j < param.length;j++) {	
				if(j == param.length - 1) {
					System.out.print(param[j].getName() + " args-" + j);
				}else {
					System.out.print(param[j].getName() + " args-" + j + ",");
				}
			}
			System.out.print(")");
			
			System.out.println();
			
		}
	}
}

效果截图:

3.7 获取异常

Class[] exceptions =  method.getExceptionTypes();

打印输出异常

Class[] exceptions =  method.getExceptionTypes();
if(exceptions.length != 0) {
	//如果有异常,则加上throws 
	System.out.print(" throws ");
}
			
for(int j = 0;j < exceptions.length;j++) {
	System.out.print(exceptions[j].getName() + " ");
}

代码示例(差不多是打印完整的方法结构)

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.junit.Test;

public class TestMethon {
	
	@Test 
	public void test2() {
		
		Class<Person> clazz = Person.class;
		
		Method[] methods =  clazz.getDeclaredMethods();
		for(Method method : methods) {
			
			//1.获取注解
			Annotation[] annotation =  method.getAnnotations();
			for(Annotation a : annotation) {
				System.out.println(a);
			}
			
			//2.获取权限修饰符
			int i = method.getModifiers();
			String str = Modifier.toString(i);
			System.out.print(str + " ");
			
			//3.获取返回类型
			Class returnType = method.getReturnType();
			System.out.print(returnType.getName() + " ");
			
			//4.获取方法名
			System.out.print(method.getName());
			
			//5.获取参数列表
			Class[] param =  method.getParameterTypes();
			System.out.print("(");
			for(int j = 0;j < param.length;j++) {	
				if(j == param.length - 1) {
					System.out.print(param[j].getName() + " args-" + j);
				}else {
					System.out.print(param[j].getName() + " args-" + j + ",");
				}
			}
			System.out.print(")");
			
			//6.获取异常
			Class[] exceptions =  method.getExceptionTypes();
			if(exceptions.length != 0) {
				//如果有异常,则加上throws 
				System.out.print(" throws ");
			}
			
			for(int j = 0;j < exceptions.length;j++) {
				System.out.print(exceptions[j].getName() + " ");
			}
			
			System.out.println();
			
		}
	}
}

效果截图:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java中的i++和++i的区别详解

    java中的i++和++i的区别详解

    这篇文章主要介绍了java中的i++和++i的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08
  • Springboot实现页面间跳转功能

    Springboot实现页面间跳转功能

    这篇文章主要介绍了Springboot实现页面间跳转功能,本文给大家分享两种方式,方法一和方法二是不冲突的,但是通常情况下如果用方法二addViewControllers,需要把方法一所写的Controller类给注释掉,需要的朋友可以参考下
    2023-10-10
  • 一文详解SpringBoot如何切换Redis的DB

    一文详解SpringBoot如何切换Redis的DB

    这篇文章主要为大家详细介绍了Spring Redis动态切换数据库的核心机制,并指出仅调用setDatabase()和resetConnection()无法真正切换数据库的根本原因,感兴趣的小伙伴可以了解下
    2025-12-12
  • Java中实现可拖放图片剪裁入门教程

    Java中实现可拖放图片剪裁入门教程

    这篇文章主要介绍了Java中实现可拖放图片剪裁入门教程,本文写给新手,分步骤讲解如何实现图片裁剪,并对每步的代码作注释,需要的朋友可以参考下
    2015-01-01
  • Java的常见热门ORM框架优缺点区别

    Java的常见热门ORM框架优缺点区别

    Java ORM框架是一种用于将Java对象映射到关系型数据库中的工具,使得开发人员能够通过对象操作数据库而不必直接使用SQL查询,Java开发变得更加高效和易于维护,选择适合你的ORM框架是根据你的需求决定的,比如你的应用场景,数据结构和技术水平等
    2024-02-02
  • SpringCloud Nacos作为配置中心超详细讲解

    SpringCloud Nacos作为配置中心超详细讲解

    这篇文章主要介绍了Springcloud中的Nacos作为配置中心,本文以用户微服务为例,进行统一的配置,结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-12-12
  • SpringBoot 整合mapstruct的实现步骤

    SpringBoot 整合mapstruct的实现步骤

    这篇文章主要介绍了SpringBoot整合mapstruct,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • MyBatis接口的简单实现原理分析

    MyBatis接口的简单实现原理分析

    这里仅仅举个简单例子来说明原理,不是完全针对MyBatis的,这种思想我们也可以应用在其他地方。地mybatis接口实现原理感兴趣的朋友一起看看吧
    2017-07-07
  • Java带返回值的方法的定义和调用详解

    Java带返回值的方法的定义和调用详解

    在java中,方法就是用来完成解决某件事情或实现某个功能的办法。方法实现的过程中,会包含很多条语句用于完成某些有意义的功能——通常是处理文本,控制输入或计算数值,这篇文章我们来探究一下带返回值的方法的定义和调用
    2022-04-04
  • SpringBoot框架中Mybatis-plus的简单使用操作汇总

    SpringBoot框架中Mybatis-plus的简单使用操作汇总

    这篇文章主要介绍了SpringBoot框架中Mybatis-plus的简单使用,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-02-02

最新评论