Java对象实例化
Java对象实例化
public class NewObject { String name; public NewObject(String[] name) { this.name = name[0]; System.out.println(“ the object is created!”); } public void write() { System.out.println(this.name); } } |
NewObject no = null; try { no = (NewObject)Class.forName(className).newInstance(); no.write(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } |
字体: 小 中 大 | 上一篇 下一篇 | 打印 | 我要投稿
public class NewObject { String name; public NewObject() { System.out.println(“ the object is created!”); } public void write() { System.out.println(“”); } } |
try { no=(NewObject)Class.forName(className).getConstructor(String.class).newInstance(names); //no=(NewObject)Class.forName(className).getConstructor(newObject[]{String.class}).newInstance(names); } catch(IllegalArgumentExceptione) { e.printStackTrace(); } catch(SecurityExceptione) { e.printStackTrace(); } catch(InstantiationExceptione) { e.printStackTrace(); } catch(IllegalAccessExceptione) { e.printStackTrace(); } catch(InvocationTargetExceptione) { e.printStackTrace(); } catch(NoSuchMethodExceptione) { e.printStackTrace(); } catch(ClassNotFoundExceptione) { e.printStackTrace(); } |
try { Constructor[] cs; cs = Class.forName(className).getConstructors(); Constructor cc = Class.forName(className).getConstructor(String[].class); no = (NewObject)cc.newInstance(new Object[]{names}); } catch (SecurityException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。