1. Description
(1) java uses builders to create instances instead of constructors
(2) For classes, in order to allow clients The most traditional way to obtain an instance of itself is to provide a public constructor.
2. Instance
The difference between the constructor and the method reflection class is that Constructor can create instances.
public class Main { public Main() { } public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException { Class c = Main.class; Constructor[] ctors = c.getConstructors(); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) { ctor = ctors[i]; if (ctor.getGenericParameterTypes().length == 0) // 需要找到默认构造函数创建实例 break; } System.out.println(ctor.newInstance().getClass().getCanonicalName()); } }
The above is the detailed content of How to create Java constructor. For more information, please follow other related articles on the PHP Chinese website!