zoukankan      html  css  js  c++  java
  • 转 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的反射机制内部实现非常的复杂,感兴趣的人可以在网上找资料看看它的实现机制。

  • 相关阅读:
    牛顿迭代法
    C语言补遗
    Manjaro添加开机启动脚本
    tensorboard查看pytorch模型
    Kindle最佳排版记录
    01背包问题详解
    差分法介绍
    BFS详解
    UVA11732 "strcmp()" Anyone?
    LA3942 Remember the Word
  • 原文地址:https://www.cnblogs.com/20158424-hxlz/p/10319591.html
Copyright © 2011-2022 走看看