Home  >  Article  >  Java  >  Very simple JAVA reflection tutorial

Very simple JAVA reflection tutorial

黄舟
黄舟Original
2017-02-07 10:35:491337browse

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)!


Statement:
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