Create a new object

Source: Internet
Author: User

For constructors, you cannot do this as you do, because executing a constructor means creating a new object (to be precise, the process of creating an object involves allocating memory and constructing objects). So, the most similar examples of the above example are:

Import java.lang.reflect.*;PublicClass Constructor2 {PublicConstructor2 () {}PublicConstructor2 (int A,int b) {System.Out.println ("A =" + A +"B =" + b);}PublicStaticvoid main (String args[]) {try { Class cls = class.forname ( "Constructor2"); Class partypes[] = new class[2]; partypes[ 0] = Integer.type; Partypes[1] = Integer.type; Constructor ct = cls.getconstructor (partypes); Object arglist[] = new object[2]; arglist[ 0] = new Integer (37); Arglist[1] = new Integer (47); Object retobj = ct.newinstance (arglist); } catch (Throwable e) {System.err.println (e);}}       

Finds the appropriate constructor based on the specified parameter type and executes it to create a new object instance. It is valuable to use this method to create objects dynamically while the program is running, rather than creating objects at compile time.

Create a new object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.