在实际开发过程中,JAVA的反射技术应用广泛,尤其是在一些广泛使用的框架中,如Spring、mybatis中更是大量使用。java语言并不是一种动态语言,也就是说在运行时不能改变程序结构或者变量类型,但是JAVA提供了反射技术,可以让我们在运行时加载所需要的类。反射的英文单词是reflect,也可以翻译成为映像,个人认为叫映像可能更好理解一些。反射技术就是在程序运行时将所需要的类通过Class.forname将类影响交给使用者使用。先看一下使用new创建类对象的方式:
public class newServiceImpl {
private String name;
public newServiceImpl(){
}
public newServiceImpl(String name){
this.name = name;
}
public void sayHello(String name){
System.err.println("Hello " + name);
}
public void sayHello(){
System.err.println("Hello " + this.name);
}
}
在newServiceImpl类中,有两个构造函数和两个sayHello方法,使用这个类的方法如下:
public class NewTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
newServiceImpl ns1 = new newServiceImpl("newService");
ns1.sayHello();
newServiceImpl ns2 = new newServiceImpl();
ns2.sayHello("newService2");
}
}
在设立我们使用了new关键字来创建类对象,这时,在编译的时候就会将newServiceImpl类加载进来并且构造。而反射机制,可以这样操作:
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);
}
使用这个类:
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;
}
}
JAVA的反射机制是通过java.lang.reflect.*来实现的,在这里,我们使用
(ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").newInstance();
(ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").getConstructor(String.class).newInstance("reflectservice2");
(ReflectServiceImpl)Class.forName("com.springstudy.reflect.ReflectServiceImpl").getConstructor(String.class).newInstance("reflectservice2");
在运行的时候来构造无参数构造器或有参数构造器的对象,实现运行时创建使用类对象的方式,这就是通过JAVA的反射机制来创建对象的方法,JAVA的反射机制内部实现非常的复杂,感兴趣的人可以在网上找资料看看它的实现机制。