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

posted @ 2019-01-25 14:48  孔乙己的茴香豆  阅读(219)  评论(0编辑  收藏  举报