反射带参与无参构造方法创建对象

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

    }

猜你喜欢

转载自blog.csdn.net/tanganq/article/details/81268054