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 @ 2022-08-28 11:58  第十八使徒  阅读(74)  评论(0)    收藏  举报