关于forName()、newInstance()、getMethod()、getClass()等区别的简略说明

因为最近频繁用到,只能是自己查查,总结一下,方便以后利用。

1、lass.forName( )静态方法的目的是为了动态加载类。在加载完成后,一般还要调用Class下的newInstance( )静态方法来实例化对象以便操作。因此,Class.forName( )是动态加载类是没有用的,其最终目的是为了实例化对象。

一般的实现方式:

String carClassName = "com.etc.test5.Car";
 //创建对象
 Car car = (Car) Class.forName(carClassName).newInstance();

2、.getClass();  //得到该对象的class,后期可能会用到getField()得到该类声明的属性,getMethod()获取方法对象。

常见用法:

Method method = car.getClass().getMethod(setterMethodName, String.class);   //其中setterMethodName是setter方法的名称,String类型。

3、invoke()方法:我理解为反射赋值,比如继续上面的代码:method.invoke(car, carPropertyValue);其中Car类中有一个name变量,那个执行invoke方法后,对象car的name值则为carPropertyValue(在之前声明过)。

总结:

forName返回Class,后需要newInstance实例化;

newInstance返回T;

getClass返回Class,后需要getMethod获取方法;

getMethod返回Method;

invoke无返回值,需要用Method的对象来调用。

现在基础知识很弱,处于写代码全靠模仿,原理知之甚少的阶段,需要一点一点的自学,加油。

原文地址:https://www.cnblogs.com/LzdDream/p/7464188.html