Home > Java > javaTutorial > body text

Very simple JAVA reflection tutorial

黄舟
Release: 2017-02-07 10:35:49
Original
1459 people have browsed it

Reflection can dynamically load classes, instantiate objects, and call methods. Now let’s take the following example to explain.

1. Load the class.

Class clazz = Class.forName("java.lang.String"); //This code gets a class object of the String class. The parameter fills in the package name.

If you use URLClassLoader, you can load the local or remote jar package, and get the specific class object through the loadclass method.

Second, instantiate the object.

If the object is instantiated through the default constructor, we can use the following method of the class object to get an object, such as

clazz..newInstance();

If by bringing Using the parameter constructor to instantiate the object can be achieved through the following code:

Constructor myConstructor = myClass.getConstructor(parameterTypes);//Get a constructor object.

                                                                                                                                                                        Where parameterTypes be Class... parameterTypes, such as String.class, int.class, etc. Then get the instantiated object through the constructor object:

myConstructor.newInstance("xxx",123); fill in the specific construction parameters in the constructor.

Third, call the method.

Method mezod = clazz.getMethod(methodName, parameterTypes); You can get the object of the method class, and then we can execute the method through the invoke method of mezod.

         mezod.invoke(obj, "xxx",123);//The first parameter is the initiating object of this method. If null is filled in, it means that the static method is called.

The article is reproduced from CSDN.NET. If there are any copyright issues, please contact us for deletion.

The above is the content of a very simple JAVA reflection tutorial. For more related content, please pay attention to the PHP Chinese website (www. php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!