java反射技术的简单应用
一.反射介绍
java反射技术的应用广泛,能够对类的方法和参数进行配置,完成对象的初始化工作,增加了java的灵活性,SpringIOC也使用了反射技术,下文主要讲解对象的构建和方法的反射调用。
二.通过反射调用对象
1.构建无参方法的类
public class ReflectService { public void hello(String name){ System.out.println("hello"+name); } public ReflectService getInsatance() { ReflectService reflectService=null; try{
//通过给类加载器一个类的全限定类名,再通过newInstance()方法初始化一个类对象
//也可以用对象.getClass();或者类.Class得到类对象
reflectService= (ReflectService)
Class.forName("com.mc74120.project_learn.config.ReflectService").newInstance();
} catch
(ClassNotFoundException|InstantiationException|IllegalAccessException exception){
ex.printStackTrace();
}
return reflectService;
} }
2.构建有参方法的类
public class ReflectService { private String name; public void hello(String name){ System.out.println("hello"+name); } public ReflectService(String name) { this.name = name; } public ReflectService getInsatance() { ReflectService reflectService=null; try{ reflectService= (ReflectService) Class.forName("com.mc74120.project_learn.config.ReflectService").getConstructor(String.class).newInstance("010"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException exception){ } return reflectService; } }
先通过forName得到类加载器,getConstructor()方法设定参数的类型,再通过newInstance()生成对象。
3.反射方法
public void reflectMethod() { Object returnObj = null; ReflectService target = null; try { target = ReflectService.class.newInstance(); Method method = ReflectService.class.getMethod("hello", String.class); returnObj = method.invoke(target, "010"); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }
//Method method = ReflectService.class.getMethod("hello", String.class);
//returnObj = method.invoke(target, "010"); target 哪个对象调用此方法,010为参数,
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架