Get the App
SLTechnology News&Howtos  ›  Development  › 

How to analyze the problem of Java reflection assigning to generic sets

Shulou Source: shulou.com Published: 2022-06-02 02:22:44 10月04日 Update

Today I'll show you how to analyze the problem of Java reflection assigning values to generic sets. The content of the article is good. Now I would like to share it with you. Friends who feel in need can understand it. I hope it will be helpful to you. Let's read it along with the editor's ideas.

Generics

Java generics are briefly described as follows:

For example, to create a List collection, I want to put only Student object information in it, which needs to be written as

List studentList = new ArrayList ()

At this time, only values of type Student can be placed in the List. If you forcibly put values of other types (such as Integer), an error message will be prompted:

Java.lang.ClassCastException: java.lang.Integer cannot be cast to com.entity.Student

According to this result, only values of type Student can be put in the studentList, there is no problem.

Then a strange thing happened when an error was found in the log of the company's project:

Java.lang.ClassCastException: java.lang.Integer cannot be cast to com.entity.Student

The original code looks like this:

Student student = studentList.get (0)

What? When the collection is created, it is obvious that the generic type is Student. Where did this String come from?

At this time, we have to put forward another concept:

Reflection

A more comprehensive explanation:

JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic information acquisition and the function of dynamically calling the methods of the object is called the reflection mechanism of java language.

To dissect a class, you must first get the bytecode file object of the class. The dissection uses the method in the Class class. So first get the Class type object corresponding to each bytecode file.

After a debug, I found this piece of code (from a method in the hutools package, which I can't remember clearly, imitating writing):

Class

Tags: Reflection problem method object type code analysis information content article time company dynamic byte that is properties files more mechanisms errors Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Technology macOS Apple Redmi