package com.bjpowernode.demo04;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
/**
* 反射创建实例(instance)
* 1)直接通过Class对象创建实例, 会调用类的无参构造方法,如果类没有无参构造产生异常
* 2)通过构造方法创建实例
* @author Administrator
*
*/
public class Test04 {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
//1) 通过Class对象创建实例
Class<?> class1 = String.class;
//class1.newInstance()创建实例时,默认会调用String类的无参构造
Object str1 = class1.newInstance(); //相当于创建了一个空的字符串对象 new String()
//Integer类没有无参构造, 不能通过class对象创建实例, 会产生异常
// Class<?> class2 = Integer.class;
// Object ii = class2.newInstance();
//2)通过构造方法创建实例
//反射构造方法 : String( byte[] bytes )
Constructor<?> constructor1 = class1.getConstructor( byte[].class );
//创建实例: constructor1.newInstance( 构造方法的实参 )
byte[] bytes = {65,66,67,68,69,70};
Object str2 = constructor1.newInstance( bytes ); //new String(bytes )
System.out.println( str2 );
//反射构造方法 : String(byte[] bytes, int from, int len)
Constructor<?> constructor2 = class1.getConstructor(byte[].class , int.class , int.class);
Object str3 = constructor2.newInstance(bytes , 0 , 3); //new String(bytes, 0 , 3)
System.out.println( str3 );
}
}
java基础回顾之反射-----反射创建实例
最新推荐文章于 2021-09-02 08:48:42 发布