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为参数,
复制代码
posted @   第十八使徒  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示