Today I learned about anti-reflection in Java basics. According to my personal understanding after studying, reflection is a set of tools for obtaining classes, attributes, methods, etc. (Actually, after learning reflection, it feels a bit like drinking cold water to quench my thirst. But I really don’t realize what it tastes like. Maybe I haven’t learned the essence. I can feel that something is missing. This is what I learned based on Java. This is the last part, I want to review it again, and then learn other things. I also want to have time to read books on JVM and computer systems. I always feel that I am not a professional, and I have some shortcomings in thinking. )
Before learning reflection, I first recalled the variable parameters.
public static void main(String[] args) { test();//调用方法1test("JAVA");//调用方法2test("JAVA","工程师");//调用方法3test(new String[]{"水果","电器"});//调用方法4 } static void test(String ... array){ //直接打印:System.out.println(array);for(String str:array){ //利用增强for遍历 System.out.println(str); } }
The reason why I recall variable parameters is because it is somewhat similar to the application of reflection. If a method is defined as a variable parameter, the restrictions on passing parameters when calling are greatly reduced. In reflection, we use some methods to get the instance object of the class, and then we can have a panoramic view of the methods, attributes, etc. in the class. As we learned in the previous study, methods, properties, etc. are divided into static and non-static, private and non-private. So when we call, which piece do we want to get, or which piece do we only want to get? Is it possible to think of a way to achieve this? At this time, reflection appeared, and now this is all I understand about it. keep it up.
1. The concept of reflection
The JAVA reflection mechanism is in the running state (note that it is not during compilation). For any class, you can know about this class. All properties and methods; for any object, any of its methods can be called; this dynamic acquisition of information and the function of dynamically calling the object's methods are called the reflection mechanism of the Java language.
The Java reflection mechanism mainly provides the following functions:
-- Determine the class to which any object belongs at runtime;
-- Construct the class of any class at runtime Object;
--Judge the member variables and methods of any class at runtime;
--Call the method of any object at runtime;
- - Generate dynamic proxies.
In JDK, the classes related to reflection mainly include the following
//
Class class
Class class under the java.lang package Instances represent classes and interfaces in a running Java application. An enumeration is a class and an annotation is an interface. Each array belongs to a class that is mapped to a Class object, which is shared by all arrays with the same element type and dimension. The basic Java types (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as Class objects.
About the explanation in the Class class JDK:
public finalclass Class<t> implements java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement {private static final int ANNOTATION= 0x00002000;private static final int ENUM = 0x00004000;private static final int SYNTHETIC = 0x00001000;private static native void registerNatives();static { registerNatives(); }/* * Constructor. Only the Java Virtual Machine creates Class * objects. */private Class() {}</t>
Some methods in the Class class JDK (I personally feel that it is very comfortable to read, and I want to record it)
public String toString() {return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))+ getName(); }//应该是三元表达式
public static Class> forName(String className)throws ClassNotFoundException { Class> caller = Reflection.getCallerClass();return forName0(className, true, ClassLoader.getClassLoader(caller), caller); }
public static Class> forName(String name, boolean initialize, ClassLoader loader)throws ClassNotFoundException { Class> caller = null; SecurityManager sm = System.getSecurityManager();if (sm != null) {// Reflective call to get caller class is only needed if a security manager// is present. Avoid the overhead of making this call otherwise.caller = Reflection.getCallerClass();if (loader == null) { ClassLoader ccl = ClassLoader.getClassLoader(caller);if (ccl != null) { sm.checkPermission( SecurityConstants.GET_CLASSLOADER_PERMISSION); } } }return forName0(name, initialize, loader, caller); }
private static native Class> forName0(String name, boolean initialize, ClassLoader loader, Class> caller)throws ClassNotFoundException;
public T newInstance()throws InstantiationException, IllegalAccessException {if (System.getSecurityManager() != null) { checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false); }// NOTE: the following code may not be strictly correct under// the current Java memory model.// Constructor lookupif (cachedConstructor == null) {if (this == Class.class) {throw new IllegalAccessException("Can not call newInstance() on the Class for java.lang.Class"); }try { Class>[] empty = {};final Constructor<t> c = getConstructor0(empty, Member.DECLARED);// Disable accessibility checks on the constructor// since we have to do the security check here anyway// (the stack depth is wrong for the Constructor's// security check to work) java.security.AccessController.doPrivileged(new java.security.PrivilegedAction<void>() {public Void run() { c.setAccessible(true);return null; } }); cachedConstructor = c; } catch (NoSuchMethodException e) {throw new InstantiationException(getName()); } } Constructor<t> tmpConstructor = cachedConstructor;// Security check (same as in java.lang.reflect.Constructor)int modifiers = tmpConstructor.getModifiers();if (!Reflection.quickCheckMemberAccess(this, modifiers)) { Class> caller = Reflection.getCallerClass();if (newInstanceCallerCache != caller) { Reflection.ensureMemberAccess(caller, this, null, modifiers); newInstanceCallerCache = caller; } }// Run constructortry {return tmpConstructor.newInstance((Object[])null); } catch (InvocationTargetException e) { Unsafe.getUnsafe().throwException(e.getTargetException());// Not reachedreturn null; } }</t></void></t>
public String getName() { String name = this.name;if (name == null)this.name = name = getName0();return name; }
// cache the name to reduce the number of calls into the VMprivate transient String name;private native String getName0();
There are many more, so I won’t record them for now. . . . .
//java.lang.reflect 包下 Constructor 代表构造函数 Method 代表方法 Field 代表字段 Array 与数组相关
2. Description of the Class class
常用的得到Class类的方法 // Class c=new Class(); 不可以,因为它被私有化了1) Class c=Student.class; //用类名.class 就可以得到Class类的实例2) Student stu=new Student(); Class c=stu.getClass(); //用对象名.getClass();3) Class c=Class.forName("com.mysql.jdbc.Driver");
//例一 通过调用无参的构造函数,创建类对象public class Test {public static void main(String[] args) throws InstantiationException, IllegalAccessException { Class clazz=Dog.class; Dog dog=(Dog)clazz.newInstance(); dog.shout(); } } class Dog{void shout(){ System.out.println("汪汪"); } }
Through Example 1, I I don’t see the benefits of using reflection, eh~~
//例二 上例的改写Class clazz=Class.forName("com.weiboo.Dog"); //注意,必须是类的全部Dog dog=(Dog)clazz.newInstance(); dog.shout();
//例三 (运行本类,Dog 和 Cat 类,必须有一个无参的构造函数)public class Test {public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException { Dog dog=(Dog)createObj(Dog.class); dog.shout(); Cat cat=(Cat)createObj(Cat.class); cat.speak(); } static Object createObj(Class clazz) throws InstantiationException, IllegalAccessException{return clazz.newInstance(); //调用的是newInstance() 方法创建的类对象,它调用的是类中无参的构造方法} } class Dog{void shout(){ System.out.println("汪汪"); } } class Cat{void speak(){ System.out.println("喵~~~"); } }
3. Description of other classes in reflection
1) Constructor
Represents the constructor in the class The Class class provides the following four methods
public Constructor>[] getConstructors() //Returns all the methods in the class Collection of public constructors, the subscript of the default constructor is 0
public Constructor
public Constructor>[] getDeclaredConstructors() //Returns all constructors in the class, including private ones
public Constructor
import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;//例子 得到某个类中指定的某个构造函数所对应的 Constructor对象class Test2 {public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Class<cat> clazz = Cat.class; Constructor<cat> c = clazz.getConstructor(int.class, String.class); Cat cat = (Cat) c.newInstance(20, "加飞猫"); cat.speak(); }class Cat {private String name;private int age;public Cat(int age, String name) {this.age = age;this.name = name; }public Cat(String content) { System.out.println("这是构造函数得到的参数" + content); }void speak() { System.out.println("喵~~~"); System.out.println("我的名字是" + this.name + "我的年龄是" + this.age); } } }</cat></cat>
/例子 访问类中的私有构造函数 Class clazz=Cat.class; Constructor c=clazz.getDeclaredConstructor(); c.setAccessible(true); //让私有成员可以对外访问Cat cat=(Cat) c.newInstance(); //对于私有的来说,能不能行?cat.speak();
2) Method represents the method in the class
Class class provides the following four methods
public Method[] getMethods() //Get the collection of all public methods, including extended inherited
public Method getMethod(String name,Class>... parameterTypes) //Get the specified public method parameter 1: method name parameter 2: parameter type set
public Method[] getDeclaredMethods() //Get all Methods (including private ones), except for inherited
public Method getDeclaredMethod(String name,Class>... parameterTypes) //Get any specified method, except for inherited ones
//调用类中的私有方法main 函数 Class clazz=Cat.class;//调用一个不带参数的方法Method m=clazz.getDeclaredMethod("speak"); m.setAccessible(true); Cat c=new Cat(); m.invoke(c); //让方法执行 //调用一个带参数的方法Method m=clazz.getDeclaredMethod("eat", int.class,String.class); m.setAccessible(true); Cat c=new Cat(); m.invoke(c, 20,"鱼"); class Cat{private String name;private int age; Cat(){ }public Cat(int age,String name){this.age=age;this. name=name; } public Cat(String content){ System.out.println("这是构造函数得到的参数"+content); } private void speak(){ System.out.println("喵~~~"); System.out.println("我的名字是"+this.name+"我的年龄是"+this.age); } private void eat(int time,String something){ System.out.println("我在"+time +"分钟内吃了一个"+something); } }
例子 查看一个类中的所有的方法名public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Class clazz=Cat.class; /*Method [] methodList=clazz.getMethods() ; //查看所有的公有方法,包扩继承的 for(Method m:methodList){ System.out.println(m.getName()); }*/Method [] methodList=clazz.getDeclaredMethods(); //查看所有的方法,包扩私有的,但不包扩继承的for(Method m:methodList){ System.out.println(m.getName()); } }
3) Field 代表字段
public Field getDeclaredField(String name) // 获取任意指定名字的成员
public Field[] getDeclaredFields() // 获取所有的成员变量,除了继承来的
public Field getField(String name) // 获取任意public成员变量,包含继承来的
public Field[] getFields() // 获取所有的public成员变量
//例子 访问字段public class Test {public static void main(String[] args) throws Exception { Class clazz=Cat.class; /* Field field= clazz.getField("home"); Cat c=new Cat(); Object obj=field.get(c); System.out.println(obj); // 家*/ Cat cat=new Cat(); Field [] fieldList= clazz.getDeclaredFields();for(Field f:fieldList){ //访问所有字段f.setAccessible(true); System.out.println(f.get(cat)); } } } class Cat{private String name="黑猫";private int age=2;public String home="家"; }
四、反射的应用
用一个例子来说明一下,比较两个同类对象中的所有字段,不同的并把它输出来。
import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;public class Test {public static void main(String[] args) throws Exception { Student stu1 = new Student(24, "李磊", "工程大学", "女"); Student stu2 = new Student(20, "王一", "师大", "男"); Map<string> map = compare(stu1, stu2);for (Map.Entry<string> item : map.entrySet()) { System.out.println(item.getKey() + ":" + item.getValue()); } }static Map<string> compare(Student stu1, Student stu2) { Map<string> resultMap = new HashMap<string>(); Field[] fieldLis = stu1.getClass().getDeclaredFields(); // 得到stu1所有的字段对象try {for (Field f : fieldLis) { f.setAccessible(true); // 别忘了,让私有成员可以对外访问Object v1 = f.get(stu1); Object v2 = f.get(stu2);if (!(v1.equals(v2))) { resultMap.put(f.getName(), "stu1的值是" + v1 + " stu2的值是" + v2); } } } catch (Exception ex) { ex.printStackTrace(); }return resultMap; } }class Student {private String name;private String school;private String sex;public Student(int age, String name, String school, String sex) {this.age = age;this.name = name;this.school = school;this.sex = sex; }private int age;public int getAge() {return age; }public void setAge(int age) {this.age = age; }public String getName() {return name; }public void setName(String name) {this.name = name; }public String getSchool() {return school; }public void setSchool(String school) {this.school = school; }public String getSex() {return sex; }public void setSex(String sex) {this.sex = sex; } }</string></string></string></string></string>
The above is the detailed content of Reflection, a basic introduction to Java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment