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

  • 相关阅读:
    SQL后台分页三种方案和分析
    SQL分页查询语句
    SQL利用临时表实现动态列、动态添加列
    查询sybase DB中占用空间最多的前20张表
    敏捷软件开发之TDD(一)
    敏捷软件开发之开篇
    Sql Server 2012启动存储过程
    改变VS2013的菜单栏字母为小写
    Sql Server获得每个表的行数
    Sql Server trace flags
  • 原文地址:https://www.cnblogs.com/20158424-hxlz/p/10319591.html
Copyright © 2011-2022 走看看