Home > Java > javaTutorial > How to create Java constructor

How to create Java constructor

王林
Release: 2023-05-09 15:25:07
forward
1365 people have browsed it

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());
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template