1. 程式人生 > >反射帶參與無參構造方法建立物件

反射帶參與無參構造方法建立物件

public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        // TODO Auto-generated method stub
        Class<?> class1 = String.class;//反射String
        //利用反射建立無參物件
        //Constructor<?> constructor = class1.getConstructor();
        Constructor<?> constructor = class1.getConstructor();
        Object newInstance = constructor.newInstance();
        
        //利用反射建立String(bytes)物件
        byte[] bytes = {97,98,101,110,120};
        Constructor<?> constructor2 = class1.getConstructor(byte[].class,int.class,int.class);//(byte[].class
        Object str2 = constructor2.newInstance(bytes,0,5);//new String(bytes)
        System.out.println(str2);//abenx

    }