GetMyName_newInstance

来源:互联网 发布:在淘宝买到假货怎么办 编辑:程序博客网 时间:2024/06/18 15:35
class GetMyName_newInstance //getName(){/*A a = (A)Class.forName("pacage.A").newInstance();这和A a = new A();是一样的效果。   JVM会执行静态代码段,要记住一个概念,静态代码是和class绑定的,class装载成功就表示执行了静态代码了,以后也就不会再走这段静态代码了。   Class.forName(xxx.xx.xx) 返回的是一个类   Class.forName(xxx.xx.xx);的作用是要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段,动态加载和创建Class 对象,比如想根据用户输入的字符串来创建对象String str = 用户输入的字符串Class t = Class.forName(str);t.newInstance();*/void sayhi(){System.out.println("sayhi()");}public static void main(String[] args) {try{Class c1 = Class.forName ("GetMyName_newInstance"); System.out.println(c1.getName());GetMyName_newInstance ins=(GetMyName_newInstance)c1.newInstance();ins.sayhi();}catch (ClassNotFoundException e){System.out.println(e);}catch(InstantiationException eins){System.out.println(eins);}catch(IllegalAccessException ell){System.out.println(ell);}}}/*GetMyName_newInstancesayhi()请按任意键继续. . .*/