Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Introduction to the principle of java reflection

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is "introduction to the principle of java reflection mechanism". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "introduction to the principle of java reflection mechanism".

Phellodendron mandshurica (Thunb.)

1 what is the reflection mechanism

The reflection mechanism is that in the running state, for any class, all the properties and methods of this class can be known; for any object, any one of its methods and properties can be called; this dynamic information and the function of dynamically calling the methods of the object is called the reflection mechanism of java language.

In an object-oriented world, everything is an object. In the Java language, are static members, ordinary data types, objects?

Whose object is the class?

First of all, the class is the object, and the class is the instance object of the java.lang.Class class.

Create a new Foo class

Foo is also an instance object, an instance object of the Class class, which is called (class type) on the official website.

Reflection is one of the features of java programming language, which allows running java programs to obtain their own information and manipulate the internal properties of classes or objects.

The core of   reflection is that JVM dynamically loads classes or calls methods / access properties at run time, and it doesn't need to know in advance (at code-time or compile-time) who the running object is.

To understand reflection, you need to know JVM, but general materials will not talk about JVM in this section. After all, learning is from shallow to deep.

2 what can the reflection mechanism do?

The reflection mechanism mainly provides the following functions:

Determine the class to which any object belongs at run time

Construct an object of any class at run time

Determine the member variables and methods of any class at run time

Call the method of any object at run time

Generate a dynamic proxy.

Note that it is obtained at run time, not at compile time. In fact, most of the time we write code directly in eclipse and ignore the compilation process.

In Eclipse, when we enter a point (such as a.) The compiler will automatically list its properties and methods, and reflection will be used here

3 API related to the reflection mechanism (here only talk about the first two of the five functions of the reflection mechanism)

The implementation of the reflection mechanism of java depends on four classes: class,Constructor,Field,Method

Get the complete package name and class name through an object

Package cn.xins08.boke

Public class TestReflect {

Public static void main (String [] args) {

TestReflect testReflect = new TestReflect ()

System.out.println (testReflect.getClass () .getName ())

/ / result: cn.xins08.boke.TestReflect

}

}

Instantiate the Class object:

There are three ways to implement the reflection mechanism to get a class:

Package cn.xins08.boke

Public class TestReflect {

Public static void main (String [] args) throws Exception {

Class class1 = null

Class class2 = null

Class class3 = null

/ / the first method (this method is often used to load data drivers in JDBC development)

Class1 = Class.forName ("cn.xins08.boke.TestReflect")

/ / third way: any object in java has a getClass method

Class2 = new TestReflect () .getClass ()

/ / the third way: any object in java has a class attribute

Class3 = TestReflect.class

System.out.println ("Class name:" + class1.getName ())

System.out.println ("Class name:" + class2.getName ())

System.out.println ("Class name:" + class3.getName ())

/ / print the result:

/ *

* Class name: cn.xins08.boke.TestReflect class name: cn.xins08.boke.TestReflect class name:

* cn.xins08.boke.TestReflect

, /

}

}

Get the interface between the parent class and the implementation of an object: package cn.xins08.boke

Import java.io.Serializable

Public class TestReflect implements Serializable {

Private static final long serialVersionUID =-2862585049955236662L

Public static void main (String [] args) throws Exception {

Class clazz = Class.forName ("cn.xins08.boke.TestReflect")

/ / get the parent class

Class parentClass = clazz.getSuperclass ()

System.out.println ("the parent of clazz is:" + parentClass.getName ())

/ / the parent class of clazz is: java.lang.Object

/ / get all the interfaces

Class intes [] = clazz.getInterfaces ()

System.out.println ("the interfaces implemented by clazz are:")

For (int I = 0; I < intes.length; iTunes +) {

System.out.println ((I + 1) + ":" + intes.getName ())

}

/ / clazz implements the following APIs:

/ / 1:java.io.Serializable

}

}

Create an instance:

There are two main ways to generate objects through reflection:

(1) use the newInstance () method of the Class object to create an instance of the corresponding class of the Class object.

Class c = String.class

Object str = c.newInstance ()

What is the difference between new and newInstance () when initializing a class and generating an instance?

The difference is that objects are created in different ways, the former using the class loading mechanism, so why are there two ways to create objects? This should be explained in terms of software ideas such as scalable, extensible, reusable and so on.

NewInstance: weak type. Inefficient. Only no-parameter constructions can be called.

New: strongly typed. Relatively efficient. Can call any public construct.

NewInstance () is the inevitable choice to realize IOC, reflection, interface programming and dependency inversion. New can only instantiate concrete classes and is not suitable for interface programming.

(2) first get the specified Constructor object through the Class object, and then call the newInstance () method of the Constructor object to create the instance. This method can construct an instance of the class with the specified constructor.

/ / get the Class object corresponding to String

Class c = String.class

/ / get the constructor of the String class with one String parameter

Constructor constructor = c.getConstructor (String.class)

/ / create an instance based on the constructor

Object obj = constructor.newInstance ("23333")

System.out.println (obj)

Note: reflection consumes some additional system resources. If you don't need to create an object dynamically, you don't need to use reflection.

At the end of the article, we discuss the factory model:

Package cn.xins08.boke

Public interface Fruit {

Public void eat ()

}

Package cn.xins08.boke

Public class Apple implements Fruit {

Public void eat () {

System.out.println (eat apples)

}

}

Package cn.xins08.boke

Public class Factory {

Public static Fruit getInstance (String className) {

If ("apple" .equals (className)) {

Return new Apple ()

}

Return null

}

}

Package cn.xins08.boke

Public class FactoryDemo {

Public static void main (String [] args) {

Fruit f = Factory.getInstance ("apple")

F.eat ()

}

}

/ / the result returned is "eat apples"

This is the simplest factory design pattern, but a big problem is that if the subclass of the interface increases, then the factory class definitely needs to be changed. The cause of this problem is new, which is different if it becomes a reflex mechanism. The instantiated object of reflection only needs a package. Class is fine.

Package cn.xins08.boke

Public interface Fruit {

Public void eat ()

}

Package cn.xins08.boke

Public class Orange implements Fruit {

Public void eat () {

System.out.println (eat oranges)

}

}

Package cn.xins08.boke

Public class Apple implements Fruit {

Public void eat () {

System.out.println (eat apples)

}

}

Package cn.xins08.boke

Public class Factory {

Public static Fruit getInstance (String className) {

Fruit fruit = null

Try {

/ / here is the class type of Fruit, which is forced to cast.

Fruit = Fruit) Class.forName (className) .newInstance ()

} catch (Exception e) {

E.printStackTrace ()

}

Return f

}

}

}

Package cn.xins08.boke

Public class FactoryDemo {

Public static void main (String [] args) {

Fruit f = Factory.getInstance ("cn.xins08.boke.Apple")

F.eat ()

}

}

At this time, we find that even if several interface subclasses are added, the factory class can still instantiate the object and correspond to all the changes.

So far you have learned the most basic reflection use, talk about this before learning Spring, and so on after learning Spring dependency injection, reverse control, I believe you will have a better understanding of reflection.

At this point, I believe you have a deeper understanding of the "introduction to the principle of java reflection mechanism". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report