Java From entry to abandonment 38—Class class
01 Class taxonomical concept
Class Class is Reflection The root of , For anything you want to load dynamically , Operation of class , You have to get the corresponding first Class object
stay Object Class defines the following methods , This method is inherited by all subclasses
public final Class getClass()// Back here Object Runtime class for . From the running results of the program, it is easy to understand , namely : You can get the name of the class through object reflection .
understand Class:
- Class It’s also a class
- Class Objects can only be created by the system
- A loaded class is in JVM There will only be one Class example
- One Class Object corresponds to a load into JVM Medium .class file
- Every instance of a class remembers who it is by Class The case claims that
- adopt Class You can get all the loaded structures in a class completely
- Class Class is Reflection The root of , For anything you want to load dynamically , Operation of class , You have to get the corresponding first Class object
Which types have Class object
- class: External class , member ( Member inner class , Static inner class ), Local inner classes , Anonymous inner class
- interface: Interface
- []: Array
- enum: enumeration
- annotation: annotation
- primitive type: Basic data type
- void
02 Class Common methods of class
return type | Method name and function description |
---|---|
static Class<?> |
forName(String className) Returns… Associated with a class or interface with the given string name Class object . |
static Class<?> |
forName(String name, boolean initialize, ClassLoader loader) Use the given class loader , Returns… Associated with a class or interface with the given string name Class object . |
<A extends Annotation> A |
getAnnotation(Class<A> annotationClass) If there is a comment of the specified type for the element , Then return these comments , Otherwise return to null. |
Annotation[] |
getAnnotations() Returns all comments that exist on this element . |
ClassLoader |
getClassLoader() Returns the class loader of this class . |
Constructor<T> |
getConstructor(Class<?>... parameterTypes) Return to one Constructor object , It reflects this Class The specified public constructor of the class represented by the object . |
Constructor<?>[] |
getConstructors() Return a Constructor An array of objects , These objects reflect this Class All the public constructors of the class represented by the object . |
Annotation[] |
getDeclaredAnnotations() Returns all comments that exist directly on this element . |
Constructor<T> |
getDeclaredConstructor(Class<?>... parameterTypes) Return to one Constructor object , The object reflects this Class The specified constructor of the class or interface represented by the object . |
Constructor<?>[] |
getDeclaredConstructors() return Constructor An array of objects , These objects reflect this Class All construction methods of class declaration represented by object . |
Field |
getDeclaredField(String name) Return to one Field object , The object reflects this Class The specified declared field of the class or interface represented by the object . |
Field[] |
getDeclaredFields() return Field An array of objects , These objects reflect this Class All fields declared by the class or interface represented by the object . |
Method |
getDeclaredMethod(String name, Class<?>... parameterTypes) Return to one Method object , The object reflects this Class The specified declared method of the class or interface represented by the object . |
Method[] |
getDeclaredMethods() return Method An array of objects , These objects reflect this Class All methods declared by classes or interfaces represented by objects , Including public 、 Protect 、 Default ( package ) Access and private methods , But not including the method of inheritance . |
Class<?> |
getDeclaringClass() If so Class Object represents a class or interface that is a member of another class , The return of the Class Object represents the declaration class of the object . |
Class<?> |
getEnclosingClass() Returns the immediate enclosing class of the underlying class . |
Constructor<?> |
getEnclosingConstructor() If it’s time to Class Object represents a local or anonymous class in the constructor , Then return to Constructor object , It represents the immediate closure constructor of the underlying class . |
Method |
getEnclosingMethod() If so Class Object represents a local or anonymous class in a method , Then return to Method object , It represents the immediate enclosing method of the underlying class . |
T[] |
getEnumConstants() If so Class Object does not represent an enumeration type , The element of the enumeration class or null. |
Field |
getField(String name) Return to one Field object , It reflects this Class The specified public member field of the class or interface represented by the . |
Field[] |
*getFields() Return a Field An array of objects , These objects reflect this Class All accessible public fields of the class or interface represented by the . |
Class<?>[] |
getInterfaces() Determine the class represented by this object or the interface implemented by the interface . |
Method |
getMethod(String name, Class<?>... parameterTypes) Return to one Method object , It reflects this Class The specified public member method of the class or interface represented by the . |
Method[] |
getMethods() Return a Method An array of objects , These objects reflect this Class Class or interface represented by object ( Including those declared by the class or interface and those inherited from the super class and super interface ) Public member Method . |
int |
getModifiers() Returns this class or interface encoded as an integer Java Language modifiers . |
String |
getName() With String The form returns this Class Entity represented by object ( class 、 Interface 、 Array class 、 Basic type or void) name . |
Package |
getPackage() Get this kind of package . |
URL |
**getResource**(String name) Find the resource with the given name . |
T |
newInstance() Create this Class A new instance of the class represented by the . |
03 Create an object of a runtime class
-
obtain Class The way the class is instantiated :
- If a specific class is known , By class class Property acquisition , This method is the most secure and reliable , Program performance is the highest .
Class clazz = Person.class
- Knowing an instance of a class , Call the getClass Method
Class clazz = person.getClass()
- Know the full class name of a class , And the class is under the classpath , It can be done by Class Class static methods forName() obtain , May throw out ClassNotFoundException
Class clazz = Class.forName("demo01.Student")
- The built-in basic data type can use the class name directly .Type
- It can also be used ClassLoader
Summary :
- No matter how many instances a class creates , There is only one Class object .
- obtain Class Object method
- adopt Class.forName(“ Package name + Class name ”) You can only get one Class object ( Reflection )
- adopt Object.getClass( ) You can also get one Class object ( The normal way to create objects is to get Class object )
- Through the static member variables of the class class get ( Each class has static member variables class)
- Only the default base type has a method : Through static member variables Type( By static final modification ) get ( Eight basic data types :byte int short double float char boolean)
- adopt Object.getClass.getSuperclass Get the type of the parent class
Program example
Create runtime Class The object of
public class ReflectionTest2 {
public static void main(String[] args) {
//1. adopt getClass
Person p1 = new Student();
Class c1 = p1.getClass();
System.out.println(c1);
//2. Recommend to use through forName
try {
Class c2 = Class.forName("org.westos.demo2.Person");
System.out.println(c2);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//3. It is recommended to use static variables class
Class c3 = Person.class;
System.out.println(c3);
//4. The unique method of the eight basic data types Type
Class c4 = Integer.TYPE;
System.out.println(c4);
//5.getSuperclass Get the parent class class
Class c5 = p1.getClass().getSuperclass();
System.out.println(c5);
}
}
class Person{
String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Student extends Person{
public Student(){
this.name=" Student ";
}
}
class Teacher extends Person{
public Teacher(){
this.name=" Teachers' ";
}
}
Running results
class org.westos.demo2.Student
class org.westos.demo2.Person
class org.westos.demo2.Person
int
class org.westos.demo2.Person
If the array type is the same , The same dimension , only one class object
public class ReflectionTest3 {
public static void main(String[] args) {
Class c1 = Object.class;
Class c2 = Comparable.class;
Class c3 = Integer.class;
Class c4 = Void.class;
Class c5 = ElementType.class;
Class c6 = Override.class;
Class c7 = Class.class;
Class c8 = int[].class;
Class c9 = int[][].class;
Class c10 = String[].class;
System.out.println(c1 );
System.out.println(c2 );
System.out.println(c3 );
System.out.println(c4 );
System.out.println(c5 );
System.out.println(c6 );
System.out.println(c7 );
System.out.println(c8 );
System.out.println(c9 );
System.out.println(c10);
}
}
Running results
class java.lang.Object
interface java.lang.Comparable
class java.lang.Integer
class java.lang.Void
class java.lang.annotation.ElementType
interface java.lang.Override
class java.lang.Class
class [I
class [[I
class [Ljava.lang.String;
Get the class name by reflection , attribute , Methods and construction methods
public class ReflectionTest {
public static void main(String[] args) throws
ClassNotFoundException {
// Write the copy class of array
Class c1 = Class.forName("java.util.concurrent.CopyOnWriteArrayList");
// Get class name
System.out.println(c1.getName());
System.out.println(c1.getSimpleName());
// Get attributes , Member variables
Field[] declaredFields = c1.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(" attribute :"+declaredField);
}
// How to get
Method[] declaredMethods = c1.getDeclaredMethods();
for (Field declaredField : declaredFields) {
System.out.println(" Method :"+declaredField);
}
// Acquired construction method
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(" Construction method :"+constructor);
}
}
}
Running results
java.util.concurrent.CopyOnWriteArrayList
CopyOnWriteArrayList
attribute :private static final long java.util.concurrent.CopyOnWriteArrayList.serialVersionUID
attribute :final transient java.util.concurrent.locks.ReentrantLock java.util.concurrent.CopyOnWriteArrayList.lock
attribute :private transient volatile java.lang.Object[] java.util.concurrent.CopyOnWriteArrayList.array
attribute :private static final sun.misc.Unsafe java.util.concurrent.CopyOnWriteArrayList.UNSAFE
attribute :private static final long java.util.concurrent.CopyOnWriteArrayList.lockOffset
Method :private static final long java.util.concurrent.CopyOnWriteArrayList.serialVersionUID
Method :final transient java.util.concurrent.locks.ReentrantLock java.util.concurrent.CopyOnWriteArrayList.lock
Method :private transient volatile java.lang.Object[] java.util.concurrent.CopyOnWriteArrayList.array
Method :private static final sun.misc.Unsafe java.util.concurrent.CopyOnWriteArrayList.UNSAFE
Method :private static final long java.util.concurrent.CopyOnWriteArrayList.lockOffset
Construction method :public java.util.concurrent.CopyOnWriteArrayList(java.util.Collection)
Construction method :public java.util.concurrent.CopyOnWriteArrayList()
Construction method :public java.util.concurrent.CopyOnWriteArrayList(java.lang.Object[])
Using attributes through reflection , Methods and construction methods
public class ReflectionTest2 {
public static void main(String[] args) throws
ClassNotFoundException, IllegalAccessException,
InstantiationException, NoSuchMethodException,
InvocationTargetException, NoSuchFieldException {
Class c1 = Class.forName("org.westos.demo4.Student");
// Using the nonparametric construction method
Student s1 = (Student) c1.newInstance();
System.out.println(s1);
// Using the parametric construction method
Constructor constructor = c1.getConstructor(String.class, int.class);
Student s2 = (Student) constructor.newInstance("Java", 11);
System.out.println(s2);
// Usage method
Method method = c1.getMethod("setAge", int.class);
method.invoke(s2,10);
System.out.println(s2.getAge());
// Use attributes
Field field1 = c1.getDeclaredField("name");
Field field2 = c1.getDeclaredField("age");
// Turn off permission access detection , The default is false[ Open permission access detection ] If it's not turned off, it could happen IllegalAccessException
field1.setAccessible(true);
field2.setAccessible(true);
// Set the value through the field ( object , value )
field1.set(s1,"JOHN");
field2.set(s1,23);
// Get value by field
System.out.println(field1.get(s1)+"|"+field2.get(s1));
}
}
class Student{
private String name;
private int age;
public Student(){
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.getName()+"|"+this.getAge();
}
}
Running results
null|0
Java|11
10
JOHN|23