本教程操作环境:windows7系统、java10版,DELL G3电脑。
1、说明
(1)java利用构建器来创建实例而不是构造器
(2)对于类而言,为了让客户端获取他本身的一个实例,最传统的方法就是提供一个公有的构造器。
2、实例
构造器和方法的反射类不同点在于,Constructor可以创建实例。
publicclassMain{ publicMain(){ } publicstaticvoidmain(String[]args)throwsIllegalAccessException,InvocationTargetException,InstantiationException{ Classc=Main.class; Constructor[]ctors=c.getConstructors(); Constructorctor=null; for(inti=0;i<ctors.length;i++){ ctor=ctors[i]; if(ctor.getGenericParameterTypes().length==0)//需要找到默认构造函数创建实例 break; } System.out.println(ctor.newInstance().getClass().getCanonicalName()); } }原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容