[JavaSE] reflection-Class usage, javase-class

Source: Internet
Author: User

[JavaSE] reflection-Class usage, javase-class

JAVA-Reflect

① Use of Class

② Reflection of methods

③ Reflection of member variables

④ Reflection of Constructor

⑤ Java class loading mechanism

 

I. In an object-oriented world, everything is an object

A Class is an object, and a Class is an instance object of the java. lang. Class.

There are three Representation Methods for instance objects of Class II.

 

// The first expression (known class name)

// Second expression (known object)

// The third expression (by the full name of the Class)

 

Package com. tsh. reflect; public class ReflectDemo {public static void main (String [] args) {Foo foo1 = new Foo (); // Instance Object of the Class // first expression (known Class name) Class c1 = Foo. class; // second expression (known object) Class c2 = foo1.getClass (); // third expression (by Class name) class c3 = null; try {c3 = Class. forName ("com. tsh. reflect. foo ");} catch (ClassNotFoundException e) {e. printStackTrace ();} // explanation on the official website: c1 and c2 indicate the class type of the Foo Class. // a class can only be an object of the Class, therefore, the output below is true System. out. println (c1 = c2); // you can create an instance object for this class through the class type of the class. try {// The constructor for this class that requires no parameters: Foo foo2 = (Foo) c1.newInstance (); foo2.print ();} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace () ;}} class Foo {void print () {System. out. println ("test ");}}

 

 

 

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.