闽公网安备 35020302035485号
//new 方式创建对象
ReflectDemo reflectDemo = new ReflectDemo();
//反射创建对象 反射创建对象的三种方式
(1)Class<ReflectDemo> reflectDemoClass = ReflectDemo.class;
(2)Class<?> aClass = Class.forName ("com.whale.springtransaction.transactiondemo.reflectdemo.ReflectDemo");
(3)Class<? extends Class> aClass = reflectDemoClass.getClass ();
二. new 对象和反射创建对象的效率对比//测试代码如下
public class ReflectDemo {
public static void main (String[] args) throws IllegalAccessException, InstantiationException {
proxyObject();
newObject();
}
// 堆代码 duidaima.com
//new 创建对象
//5
public static void newObject(){
long startTime = System.currentTimeMillis ();
int i;
for (i = 0; i < 100000000; i++) {
ReflectDemo reflectDemo = new ReflectDemo ();
}
if (i == 100000000) {
long endTime = System.currentTimeMillis ();
System.out.println ("new耗时为:" + (endTime - startTime));
}
}
// 堆代码 duidaima.com
//反射 创建对象
//30
public static void proxyObject() throws IllegalAccessException, InstantiationException {
long startTime = System.currentTimeMillis ();
Class<ReflectDemo> reflectDemoClass = ReflectDemo.class;
int i;
for (i = 0; i < 100000000; i++) {
ReflectDemo reflectDemo = reflectDemoClass.newInstance ();
}
if (i == 100000000) {
long endTime = System.currentTimeMillis ();
System.out.println ("反射耗时为:" + (endTime - startTime));
}
}
}

4.JIT 无法优化
4.利用反射,在泛型为int的arryaList集合中存放一个String类型的对象