Java反射之通过反射获取一个对象的方法信息(实例代码)
作者:jingxian 时间:2021-08-07 15:14:46
以下代码为一个工具类
package com.imooc.reflect;
import java.lang.reflect.Method;
public class ClassUtil {
public static void printClassMessage(Object obj){
//要获取类的信息,首先要获取类的类类型
Class c = obj.getClass();//传递的是哪个子类的对象,c就是该子类的类类型
//获取类的名称
System.out.println("类的名称为:"+c.getName());
/*
* Method类,方法对象
* 一个成员方法就是一个Method对象
* getMethods()方法获取的是所有的public的函数,包括父类继承而来的
* getDeclaredMethods()获取的是所有该类自己声明的方法,部位访问权限
*/
Method[] methods = c.getMethods();
//
for(int i=0;i<methods.length;i++){
//得到方法的返回值类型的类类型
Class returnType = methods[i].getReturnType();
System.out.print(returnType.getName()+" ");
//得到方法的名称
System.out.print(methods[i].getName()+"(");
//获取参数类型--》得到的参数列表的类型de类类型
Class[] paramType = methods[i].getParameterTypes();
for(Class class1:paramType){
System.out.print(class1.getName()+",");
}
System.out.println(")");
}
}
}
//output:
//类的名称为:java.lang.String
//boolean equals(java.lang.Object,)
//java.lang.String toString()
//int hashCode()
//.......
以下代码为测试类:
package com.imooc.reflect;
public class TestClassUtil {
public static void main(String[] args) {
String string = "hello";
ClassUtil.printClassMessage(string);
Integer n1 = 1;
ClassUtil.printClassMessage(n1);
}
}
截图如下:
标签:java,反射,对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java使double保留两位小数的多方法 java保留两位小数
2023-06-17 14:01:30
maven profile动态选择配置文件详解
2023-11-05 22:05:20
![](https://img.aspxhome.com/file/2023/4/64514_0s.png)
基于javaMybatis存进时间戳的问题
2023-11-29 02:55:51
详解java中的PropertyChangeSupport与PropertyChangeListener
2023-10-20 06:19:27
SpringBoot之Helloword 快速搭建一个web项目(图文)
2023-08-23 17:36:21
![](https://img.aspxhome.com/file/2023/8/58448_0s.jpg)
Android用过TextView实现跑马灯效果的示例
2023-07-27 11:16:54
spring boot 使用profile来分区配置的操作
2022-11-27 22:55:15
![](https://img.aspxhome.com/file/2023/5/64205_0s.png)
一文详解Reactor模型与实现示例
2023-11-13 12:22:09
![](https://img.aspxhome.com/file/2023/6/59396_0s.png)
HttpsURLConnection上传文件流(实例讲解)
2022-03-02 16:54:47
OpenCV实现人脸识别简单程序
2023-07-07 00:31:12
Stream distinct根据list某个字段去重的解决方案
2022-06-22 22:23:26
![](https://img.aspxhome.com/file/2023/0/62380_0s.png)
Java使用备忘录模式实现过关类游戏功能详解
2022-11-30 08:52:51
![](https://img.aspxhome.com/file/2023/2/60782_0s.png)
web.xml SpringBoot打包可执行Jar运行SpringMVC加载流程
2023-11-24 07:40:52
![](https://img.aspxhome.com/file/2023/9/59929_0s.jpg)
避免sql注入_动力节点Java学院整理
2023-08-21 17:39:12
RestTemplate自定义请求失败异常处理示例解析
2021-12-03 22:13:17
![](https://img.aspxhome.com/file/2023/0/60700_0s.png)
SpringBoot参数校验与国际化使用教程
2021-11-13 15:52:21
![](https://img.aspxhome.com/file/2023/8/61568_0s.png)
SpringBoot实现Mysql使用MD5进行密码加密的示例
2022-11-24 23:14:16
![](https://img.aspxhome.com/file/2023/6/62156_0s.png)
java判断字符串是否为数字的方法小结
2023-11-25 05:54:52
Flutter图片缓存管理ImageCache原理分析
2023-08-20 23:26:19
Java基于zxing生成二维码矩阵过程解析
2023-11-23 06:04:06
![](https://img.aspxhome.com/file/2023/5/59845_0s.png)