This is the 21st day of my participation in the August Text Challenge.More challenges in August
⭐ August update challenge day 21 ⭐, review and consolidate Java😁 with friends
Code shrimp is a sand carving and funny boy who likes listening to music, playing games and writing as well as most of his friends. The days are still very long, let’s refuel our efforts together 🌈
Welcome to follow my public account: JavaCodes, the name is with Java but the scope can be more than Java field oh 😁, will share blog posts or welfare for a long time, looking forward to your attention ❤
😉 offer yourself
Self-introduction, to everyone recommend their column 😁, welcome small partners to collect attention 😊
The small white to learn Java
MybatisPlus column
App crawler Column
PC side crawler column
Big factory interview question column
Overview of Java reflection
What’s the use of the reflex mechanism?
Bytecode files can be manipulated through reflection mechanisms in the Java language. The advantages are similar to hackers. Bytecode files can be read and modified. Code fragments can be manipulated through reflection. (Class file)
Under what package are the related classes for reflection mechanisms?
java.lang.reflect.*
What are the important classes related to reflection mechanisms?
Java.lang. Class: represents the entire bytecode, represents a type, represents the entire Class. Java.lang.reflect. Method: represents the Method bytecode in the bytecode. Represents a method in a class. Java. Lang. Reflect. Constructor: on behalf of the Constructor of the bytecode bytecode. Represents a constructor in a class. Java.lang.reflect. Field: represents the attribute bytecode in the bytecode. Represents a member variable in a class (static + instance variable)
2. Three ways to get a Class
2.1. The first type
Class c = class.forname (” full Class name with package name “);
try {
Class c1 = Class.forName("java.lang.String"); //c1 represents a String. Class c2 = class.forname ("java.util.Date"); //c2 represents the Date type Class c3 = class.forname ("java.lang.Integer"); Class c4 = class.forname ("java.lang.System"); } catch (ClassNotFoundException e) {e.printstackTrace (); }Copy the code
Class.forName()
- A static method
- The argument to the method is a string
- All a string needs is a full class name
- The full class name must be accompanied by the package name. The java.lang package cannot be omitted
2.2. The second
Class c = object.getClass ();
public static void main(String[] args) {
Class c1 = null;
Class c2 = null;
Class c3 = null;
try {
c1 = Class.forName("java.lang.String");
c2 = Class.forName("java.util.Date");
c3 = Class.forName("java.lang.Integer");
Class c4 = Class.forName("java.lang.System");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String str = "abcd"; // String object
Class aClass = str.getClass(); //aClass represents the bytecode file of string. class, and aClass represents the type Stirng
System.out.println(aClass == c1); //true (== the memory address of the object)
Date date = new Date();
Class cdate = date.getClass();
System.out.println(cdate == c2); //true(cdate and c2 hold the same memory address, both point to the bytecode file in the method area)
}
Copy the code
2.3. The third type
Class c = any type. Class;
public static void main(String[] args) {
Class c1 = null;
Class c2 = null;
Class c3 = null;
try {
c1 = Class.forName("java.lang.String");
c2 = Class.forName("java.util.Date");
c3 = Class.forName("java.lang.Integer");
Class c4 = Class.forName("java.lang.System");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Any type in the Java language, including basic data types, has a.class attribute
Class stringClass = String.class; //stringClass indicates the Stirng type
Class dateClass = Date.class; //dateClass represents the Date type
System.out.println(stringClass == c1);
System.out.println(dateClass == c2);
}
Copy the code
Instantiate objects by reflection
public class Main {
public static void main(String[] args) {
try {
// Use reflection to get the Class and instantiate the object
Class aClass = Class.forName("com.dong.Person");
Object o = aClass.newInstance();
System.out.println(o);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch(InstantiationException e) { e.printStackTrace(); }}}/ / the Person class
class Person {}Copy the code
Successful object creation
The newInstance() method completes the object creation by calling the Person class’s no-argument constructor.
class Person {
public Person(a) {
System.out.println("Run no-parameter constructor"); }}Copy the code
An error is reported if a parameterized constructor is defined but no parameterless constructor is present
class Person {
private String name;
public Person(String name) {
this.name = name; }}Copy the code
Therefore, it is generally best to bring the no-parameter constructor
4. Access object properties through reflection
Student class
public class Student {
private String name;
protected int age;
boolean sex;
public int no;
public static final double MATH_PI = 3.1415926;
}
Copy the code
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
Class student = Class.forName("com.dong.Student");
Object o = student.newInstance(); //o is the Student object.
// Get the no attribute (Field by attribute name)
Field no = student.getDeclaredField("no");
no.set(o,123); // Assign 123 to the no property of obj
System.out.println(no.get(o));
}
Copy the code
Get private property
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
Class student = Class.forName("com.dong.Student");
Object o = student.newInstance(); //o is the Student object.
// Get the private name
Field name = student.getDeclaredField("name");
// Assign a value to the name attribute
name.set(o,"Leathery shrimp");
System.out.println(name.get(o));
}
Copy the code
Access error
Solution: Break the encapsulation
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
Class student = Class.forName("com.dong.Student");
Object o = student.newInstance(); //o is the Student object.
// Get the private name
Field name = student.getDeclaredField("name");
// Break the encapsulation
name.setAccessible(true);
// Assign a value to the name attribute
name.set(o,"Leathery shrimp");
System.out.println(name.get(o));
}
Copy the code
SetAccessible (true) When set to this, private is also accessible externally
Cons: Breaking the encapsulation may leave room for criminals!!
5. Call methods via reflection (emphasis)
The User class
public class User {
int no;
int age;
/** * Login method */
public boolean login(String name,String password) {
if ("admin".equals(name) && "123".equals(password)) {
return true;
}
return false;
}
/** * exit */
public void logout(a) {
System.out.println("The system has been safely logged out."); }}Copy the code
test
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class aClass = Class.forName("com.dong.User");
// Create an object
Object obj = aClass.newInstance();
/ / access Method
Method login = aClass.getDeclaredMethod("login", String.class, String.class);
Object admin = login.invoke(obj, "admin"."123");
System.out.println(admin);
Method logout = aClass.getDeclaredMethod("logout"); logout.invoke(obj); }}Copy the code
GetDeclaredMethod () : Parameter 1: specifies the name of the obtained method, parameter 2: specifies the parameter list of the obtained method
Invoke () : Parameter 1: the caller of a method, parameter 2: an argument that assigns a value to a method parameter
The reflection mechanism makes the code very universal. The content that can be changed is written to the configuration file. After modifying the configuration file in the future, the object created is different, the method called is different, but the Java code does not need to change anything. This is the launch mechanism capability.
6. Invoke the specified constructor via reflection mechanism
public class Main {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class aClass = Class.forName("com.dong.User");
Constructor declaredConstructor = aClass.getDeclaredConstructor(int.class, int.class);
Object o = declaredConstructor.newInstance(1.2); System.out.println(o); }}Copy the code
GetDeclaredConstructor () : Arguments: a list of arguments specifying the constructor
❤ finally
I am aCode pipi shrimp, a prawns lover who loves to share knowledge, will update useful blog posts in the future, looking forward to your attention!!
Creation is not easy, if this blog is helpful to you, I hope you can == one key three even oh! Thank you for your support. See you next time