Java basics-Class class, java basics-Class

Source: Internet
Author: User

Java basics-Class class, java basics-Class

The java Class is the basis of the java reflection mechanism. Through the Class, we can obtain information about a Class. Next, let's take a look at the knowledge about the Class in java!

Java. lang. Class is a special Class used to encapsulate information about classes (including classes and interfaces) installed into the JVM.

When a Class or interface is loaded into the JVM, a java. lang. Class Object associated with it is generated. You can access the detailed information of the loaded Class through this Class object.

To put it simply, you can obtain the Class object corresponding to a Class through the following three methods:

1. getClass method of Object
The getClass method is defined in java. lang. Object:

Public final Class getClass ()

All Java objects use this method. This method is used to return the Class object associated with the Class that calls the method object. For example:

Date date1 = new Date ();

Date date2 = new Date ();

Class c1 = date1.getClass ();

Class c2 = date2.getClass ();

System. out. println (c1.getName (); // java. util. Date

System. out. println (c1 = c2); // true

In the above Code, calling the getClass method of the Date object date1 will return the Class object used to encapsulate the Date Class information. The getName method of the Class is called here:

Public String getName ()

The meaning of this method is intuitive, that is, the name of the encapsulated class is returned.

Note that the getClass methods of date1 and date2 in the Code return the same Class Object (the value of c1 = c2 is true ). This is because, for the same Class, JVM will load only once, and only one Class object corresponding to the Class will exist, no matter how many objects the Class instantiates.

In addition, when an object is referenced by its parent class or its implemented interface type, the getClass method returns the Class object associated with the actual Class of the object. For example:

List list = new ArrayList ();

System. out. println (list. getClass (). getName (); // java. util. ArrayList

In the code above, the Statement list. the getClass () method returns the java class to which the list object actually belongs. util. the Class object corresponding to ArrayList is not java. util. the Class object corresponding to the List. Sometimes you can use this method to understand the runtime type of an object, for example:

HashSet set = new HashSet ();

Iterator it = set. iterator ();

System. out. println (it. getClass (). getName (); // java. util. HashMap $ KeyIterator

From the code, we can see that the iterator method of HashSet returns the HashMap internal class (KeyIterator) object that implements the Iterator interface.

Because abstract classes and interfaces cannot instantiate objects, you cannot use the getClass method of objects to obtain Class objects associated with abstract classes and interfaces.

2. Use. class
The class object corresponding to the Class is returned by adding ". class" to the Class name. For example:

Class clazz = String. class;

System. out. println (clazz. getName (); // java. lang. String

This method can directly obtain the Class object associated with the specified Class without the existence of the Class Object.

3. Use the Class. forName Method
Class has a famous static method forName:

Public static Class forName (String className) throws ClassNotFoundException

This method obtains the Class object associated with the Class according to the Class name specified by the string parameter. If the class has not been loaded, this method will load the class into JVM.

This method declaration throws a ClassNotFoundException exception. As the name suggests, this exception is thrown when the method cannot obtain the class to be loaded (for example, this class does not exist in the current class path.

For example, if the current class path contains the Foo class:

Package org. whatisjava. reflect;

Public class Foo {

Public Foo (){

System. out. println ("Foo ()");

}

Static {

System. out. println ("Foo is initialized ");

}

}

Run the following code:

Class clazz = Class. forName ("org. whatisjava. reflect. Foo ");

The console has the following output:

Foo is initialized

Class. forName ("org. whatisjava. reflect. Foo") First loads the reflection. Foo Class into JVM and returns the associated Class object. After the JVM loads the Foo class, it initializes it and calls the code in its static block. Note that the parameter of the forName method is the full qualified name (including the package name) of the class ).

Different from the previous two methods for getting Class objects. The Class of the corresponding Class object to be obtained using the Class. forName method can be given through a string. This method is usually used to dynamically load the Class according to the Class name during the program running and obtain the corresponding Class object.
 

Through the above article, I believe you have a certain understanding of the reflection mechanism of java and a clear understanding of the usage of Class classes in java, in our actual work, we will be able to have a deeper understanding of the java reflection mechanism when we constantly use java knowledge to solve problems in the actual Lake!




When a Java program is running, the system always identifies all objects during the Java runtime. This information records the class to which each object belongs. Generally, virtual machines use the correct method for running type information. The Class used to save these types of information is the Class. The Class encapsulates the status of an object and an interface during runtime. When a Class is loaded, Class objects are automatically created.
Class does not have a public constructor. The Class object is automatically constructed by the Java Virtual Machine during Class loading and by calling the defineClass method in the Class loader. Therefore, a Class object cannot be explicitly declared.
Virtual machines manage a unique Class Object for each type. That is to say, each Class (type) has a Class object. When running a program, the Java Virtual Machine (JVM) first checks whether the Class object corresponding to the Class to be loaded has been loaded. If the file is not loaded, JVM searches for the. class file based on the Class name and loads its class object.
The basic Java types (boolean, byte, char, short, int, long, float, and double) and keywords void also correspond to a Class object.
Each array is a Class mapped to a Class Object. All arrays with the same element type and dimension share the Class object.
Generally, a Class object of a Class is loaded into the memory, which is used to create all objects of this Class.

1. How to get the Class object? Three methods are available:
1. Call the getClass () method of the Object Class to obtain the Class Object. This is also the most common method for generating Class objects. For example:
MyObject x;
Class c1 = x. getClass ();
2. Use the static forName () method in the Class to obtain the Class object corresponding to the string. For example:
Class c2 = Class. forName ("MyObject"), and Employee must be the interface or Class name.
3. The third method for retrieving Class objects is very simple. If T is a Java type, T. class represents a matched class object. For example
Class cl1 = Manager. class;
Class cl2 = int. class;
Class l3 = Double []. class;
Note: Class objects only describe the type, which is not necessarily a Class or interface. For example, the int. class above is a Class object. For historical reasons, the getName method of the array type returns a strange name. Ii. Common Methods for Class classes
1. getName ()
A Class Object describes the attributes of a specific Class, the most common method in the Class, getName, returns the Object Name (Class, interface, array Class, basic type, or void) represented by this Class object in the form of String. 2. newInstance ()
Class also has a useful way to create an instance for the Class, which is called newInstance (). For example:
X. getClass. newInstance (), creates a new instance of the same type as x. The newInstance () method calls the default constructor (No parameter constructor) to initialize the new object. 3. getClassLoader ()
Returns the class loader of the class. 4. getComponentType ()
Returns the Class of the Array Component type. 5. getSuperclass ()
Returns the Class that represents the superclass of the object (Class, interface, basic type, or void) represented by this Class. 6. isArray ()
Determines whether the Class object represents an array Class. Iii. Some Usage skills of Class
1. forName and newInstance can be used together to create an object based on the class name stored in the string. For example
Object obj = Class. forName (s). newInstance (); 2. The virtual machine manages a unique Class Object for each type. Therefore, you can use the = Operator to compare class objects. For example:
If (e. getClass () = Employee. class )...

Class (in the java. lang Package, Instances of the class Classrepresent classes and interfaces in a running Javaapplication ):
In Java, each class has a corresponding Class object. That is to say, when we compile a class and compile it, a Class object will be generated in the generated. class file to indicate the type information of this Class.
Three methods for getting a Class instance:
(1) Use an object to call the getClass () method to obtain the Class instance of this object;
(2) Use the static method forName () of the Class to obtain a Class instance (staticClass forName (String className) using the Class name) returns the Classobject associated with the class or interface with the given stringname .);
(3) Use the. class method to obtain the Class instance. For the encapsulation Class of the basic data TYPE, you can also use. TYPE to obtain the corresponding class instance of the basic data TYPE.
The default constructor ObjectnewInstance () in the newInstance () call class (you can refer to the instance of this class when you do not know the name of this class) creates a new instance of the class represented by this Classobject.
During running, if we want to generate a Class object, the Java Virtual Machine (JVM) checks whether the Class object of this type has been loaded. If the file is not loaded, JVM will find the. class file based on the class name and load it. Once a Class object of a certain type has been loaded into the memory, it can be used to generate all objects of this type.

 1 public class ClassTest {
2 public static void main(String [] args)throws Exception{
3 String str1="abc";
4 Class cls1=str1.getClass();
5 Class cls2=String.class;
6 Class cls3=Class.forName("java.lang.String");
7 System.out.println(cls1==cls2);
8 System.out.println(cls1==cls3);
9 }
10 }

The returned results are true and true.
Explanation: a virtual machine generates only one bytecode, which can be used to generate multiple instance objects.

 

Reflection

Reflection maps various components in the Java class into corresponding java classes. For example, a Java Class is represented by an object of A Class, and the components of a Class: member variables, methods, constructor methods, packages, and other information are also represented by Java classes, just like a car is a class, the engine and gearbox in a car are also a class. Indicates that the Class display of the Java Class provides a series of methods to obtain the variables, methods, constructor methods, modifiers, packages, and other information, the information is represented by the instance objects of the corresponding class, such as Field, Method, Contructor, and Package.

Each member of a Class can be represented by an instance object of the corresponding reflection API Class. After you call the Class method to obtain these instance objects, what is the use of these instance objects? How to use it? This is the key point of learning and application reflection.

Reflection application of Constructor

Consturctor (Consturctor) class represents a constructor in a class.

@ 1 @ get all Constructor methods of A Class: for example, Constructor [] constructors = Class. forName ("java. lang. String"). getConstructors ();

@ 2 @ get a Constructor constructor = Class. forName ("java. lang. String"). getConstructor (StringBuffer. class );

@ 3 @ create Instance Object: common method: String str = new String (new StringBuffer ("abc "));
Reflection Method: String str = (String) constructor. newInstance (new StringBuffer ("abc "));

 


Class is the implementation of defining a specific Class in Java. A class definition includes member variables, member methods, interfaces implemented by the class, and the parent class of the class. The Class object is used to represent the classes and interfaces in the currently running Java application. For example, each array belongs to a Class object, and all arrays with the same element type and dimension share a Class object. The basic Java types (boolean, byte, char, short, int, long, float, and double) and void can also be expressed as Class objects.


The following example uses a Class object to display the Class name of an object:
Void printClassName (Object obj ){
System. out. println ("The class of" + obj +
"Is" + obj. getClass (). getName ());
}


We all know that all java classes inherit the object class, and there is a method in the object class: getclass (). this method is used to obtain the reference of the Class object that has been instantiated by this Class. This reference points to the Class Object (a bit awkward ). We cannot generate a Class object by ourselves (the constructor is private), and the Class object is automatically created by the Java Virtual Machine when various classes are called in, or use the defineClass method in the class loader. The generated object will have a field to record the location of the object's CLass in the CLass object. As shown in:
 
Class
We can treat the objects of each Class as proxies of many classes. In addition, each Class object contains a field to record the Class loader of the Class referenced by it. If this field is null, the loader of this class is bootstrap loader. For details, see the Introduction to the class loader.
 
 
We know that there are multiple loaders in java, and each loader can load multiple classes. Therefore, as long as a Class Object is obtained, you can use its getClassLoader () method to obtain reference for this Class loader.
Jvm is a Class Object unique to each type of manager. Therefore, we can use the equal sign operator to compare objects: a1.getClass () = A. class; the returned value is true.
Class and loader
ForName (String classname) and forName (String classname, boolean initialze, ClassLoader loader) Methods
This method returns the de> Classde> object corresponding to the given string name. If a complete path name of a class or interface is given, this method attempts to locate, load, and connect the class. If the operation succeeds, this class object is returned. Otherwise, a ClassNotFoundException exception is thrown. For example, the following code snippet returns the run de> Classde> descriptor named de> java. lang. Threadde>. De> Class t = Class. forName ("java. lang. thread "); This method requires the class loader to be specified. When the forName method with only one String parameter is used, the Class Object calls the current Class loader by default as the loader and sets the second parameter to true. The second parameter description: If it is false, the forName method is called only when the command Class Loader loads the class, instead of initializing the static block of the class. Only when the class is instantiated for the first time, the static block is called. If this parameter is set to true, the static block is called during loading. De>
GetClassLoader ()
Obtains the class loader of this class.
GetComponentType ()
If the current Class represents an array, the Class Object of the array component is returned. Otherwise, null is returned.
GetConstructor (Class [])
Returns the specified public constructor of the Class represented by the current Class object.
GetConstructors ()
Returns an array of all public constructor sub-objects of the Class represented by the current Class object.
GetDeclaredConstructor (Class [])
Returns a specified constructor of the Class represented by the current Class object.
GetDeclaredConstructors ()
Returns an array of all the described constructor sub-objects of the Class represented by the current Class object.
GetDeclaredField (String)
Returns a specified domain object of the Class or interface represented by the current Class object.
GetDeclaredFields ()
Returns an array of all specified domain objects of the Class or interface represented by the current Class object.
GetDeclaredMethod (String, Class [])
Returns a method object specified for the Class or interface represented by the current Class object.
GetDeclaredMethods ()
Returns an array of all the described methods of the Class or interface represented by the Class object.
GetField (String)
Returns the specified public member domain object of the Class or interface represented by the current Class object.
GetFields ()
Returns an array of all accessible public domain objects of the Class or interface represented by the current Class object.
GetInterfaces ()
Returns the class or interface implemented by the current object.
GetMethod (String, Class [])
Returns the specified public member method object of the Class or interface represented by the current Class object.
GetMethods ()
Returns an array of all public member method objects of the Class or interface represented by the current Class object, including declared and inherited methods from the parent Class.
GetModifiers ()
Returns the Java language modifier code for this class or interface.
GetName ()
Returns the complete path name string of the type (Class, interface, array, or base type) represented by the Class object.
GetResource (String)
Search for resources by specified name.
GetResourceAsStream (String)
Search for resources by name.
GetSigners ()
Obtain the class tag.
GetSuperclass ()
If this Object represents any class other than the Object, the parent class Object of this Object is returned.
IsArray ()
If the Class object represents an array, true is returned; otherwise, false is returned.
IsAssignableFrom (Class)
Determine whether the Class object represents the same Class or interface or its parent Class as the Class or interface specified by the parameter.
IsInstance (Object)
This method is a dynamic equivalent method for Java instanceof operations.
IsInterface ()
Determines whether the specified Class object represents an interface type.
IsPrimitive ()
Determines whether the specified Class object represents a Java base type.
NewInstance ()
Create a new instance of the class.
ToString ()
Converts an object to a string.

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.