After some time in Java learning, you may often hear the word reflex, which means that Java has learned a higher level. Next, I'll take a step-by-step with you to uncover the mysteries of Java's advanced features reflection.
The concept of the following class object is introduced first, and may often be used in this concept:
class object : Java has a very classic words, "Everything is the object", I believe we are not unfamiliar, this sentence tells us one of the characteristics of Java, that is object-oriented. We are all familiar with the concept of classes in Java, since everything is an object, so who is the object of the class? < The concept of an object: an instance of a class > In other words, whose instance the class is. So there is the concept of class object. In Java there is a class whose name is class, and any class is an object of this class.
Here's a few lines of code to show you how to get a class object:
1. Create a new package Com.cx.bean, creating a class book under the package
Book.java file
PackageCom.cx.bean; Public classBook {Private intID; PrivateString name; PrivateString type; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString GetType () {returntype; } Public voidsetType (String type) { This. Type =type; }}
1. Create a new package Com.cx.main, creating a class test under the package.
Test.java file
PackageCom.cx.main;
ImportCom.cx.bean.Book; Public classTest { Public Static voidMain (string[] args) {Class C1=NULL; Class C2=NULL; Class C3=NULL;/*** Get Class object: Class object itself is a class*/ //The first way: the Static forname () method parameter of the class object is the complete classpath name Try{C1= Class.forName ("Com.cx.bean.Book"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } System.out.println ("The first Kind:" +C1);//: Class Com.cx.bean.Book//the second way: Get the Class object through the GetClass () method of the class instanceBook bo=NewBook (); Object ob=o; System.out.println ("Second type:" +Ob.getclass ()); //The third type: class name.C3=book.class; System.out.println ("Third type:" +C3); }}
/**
Operation Result:
First type: Class Com.cx.bean.Book
The second type: Class Com.cx.bean.Book
The third type: Class Com.cx.bean.Book
This code allows you to clearly show how to get a class object.
*/
Java Advanced Reflection: How the Reflection base gets a class and how to get all the properties and methods of the class (1)