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
}
本文通过Java代码示例介绍了如何使用反射机制创建不同类型的String对象,包括无参构造创建对象和通过字节数组创建对象的过程。

1554

被折叠的 条评论
为什么被折叠?



