• 转 java


    转 https://blog.csdn.net/nch_ren/article/details/78814080

    1.创建service实现类

    package com.springstudy.reflect;
    public class ReflectServiceImpl {
    private String name;
    public ReflectServiceImpl(){
    }
    public ReflectServiceImpl(String name){
        this.name = name;
    }
    public void sayHello(){
        System.err.println("Hello " + this.name);
    }
    public void sayHello(String name){
        System.err.println("Hello " + name);
    }
    }

    2.创建测试类

    import java.lang.reflect.InvocationTargetException;
    public class ReflectTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ReflectServiceImpl rs1 = getInstance();
        rs1.sayHello("reflectservice1");
        ReflectServiceImpl rs2 = getInstance2();
        rs2.sayHello();
    }
    public static ReflectServiceImpl getInstance(){
        ReflectServiceImpl object = null;
        try{
            object = (ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").newInstance();
        }catch(ClassNotFoundException|InstantiationException|IllegalAccessException ex){
            ex.printStackTrace();
        }
        return object;
    }
    public static ReflectServiceImpl getInstance2(){
        ReflectServiceImpl object = null;
        try{
    object = (ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").
    getConstructor(String.class).newInstance("reflectservice2");
    }catch (ClassNotFoundException | InstantiationException 
    | IllegalAccessException | NoSuchMethodException 
    | SecurityException | IllegalArgumentException 
    | InvocationTargetException ex) {
        ex.printStackTrace();
        }
        return object;
        }
    }

    3.总结

    JAVA的反射机制是通过java.lang.reflect.*来实现的,在这里,我们使用
    (ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").newInstance();
    (ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").getConstructor(String.class).newInstance("reflectservice2");
    在运行的时候来构造无参数构造器或有参数构造器的对象,实现运行时创建使用类对象的方式,这就是通过JAVA的反射机制来创建对象的方法,JAVA的反射机制内部实现非常的复杂,感兴趣的人可以在网上找资料看看它的实现机制。

  • 相关阅读:
    DEEP COMPRESSION小记
    python中join的用法
    Ubuntu下pycharm安装
    java.lang.ClassNotFoundException
    12种排序算法(转载)
    会场安排问题
    在GitHub上上传项目(转载)
    实现prim算法
    经典进程同步与互斥习题总结
    实现迪杰斯特拉算法
  • 原文地址:https://www.cnblogs.com/20158424-hxlz/p/10319591.html
Copyright © 2020-2023  润新知