The reflection mechanism obtains three ways of the class object:

Source: Internet
Author: User

person person = new person ();

1, through the GetClass () method of the object class: (Need to instantiate an object first)

Class clazz1 = person. getclass ();

2. Get objects by object instance method: (You need to instantiate an object first)

Class clazz2 = person. class;

3. The full path of the class: (No, no, No. Instance object)

Class clazz3 = class. forname ("Com.cn.Person") ;

For classes with empty constructors, you can get an instance directly from a bytecode file:

Object OBJT = Clazz.newinstance (); The null parameter constructor is called (if not, an error occurs);

For a class that does not have an empty constructor, it needs to get to his construction object before getting the instance through the constructor class

1. Get the constructor function

Constroctor Const = Clazz3.getconstructor (String.class,int.class);

2, initialization of object by Newinsttance method of constructor object

Object obj = Const. Newinstance ("Tom", 30);

The reflection mechanism obtains three ways of the class 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.