java-basic-reflection


content from : http://tutorials.jenkov.com/java-reflection/index.html

Class Name

The fully qualified class name(including package name) is obtained using the getName() like this:

Class c = new String();// obtain Calss object.
String className = c.getName(); //get Name including package name.

if you want the class name without the package name you can obtain it using the getSimpleName() method, like this:

Class c = new String();
String simpleClassName = c.getSimpleName();

Modifiers

You can access the modifiers of a class via the Class object. The class modifiers are the keywords “public”, “private”, “static” etc. You obtain the class modifiers like this;

获取类的修饰符加密后的编码。

Class c = new String();
int modifers = c.getModifiers();

这里的 getModifiers()方法会返回一个int数值;我们来看看源码解释。
在这里插入图片描述
The modifiers consist of the Java Virtual Machine’s constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier.
这些modifers由JVM的常量组成,经过加密后得到一个int数值,可以使用Modifier()方法去解密。

这里我们使用String 来示例
在这里插入图片描述
以下是代码和输出:可以看到 String类,是public final的,所以使用isFinal()和isPublic()都会返回true
在这里插入图片描述
以下是Modifier 类的一些常用的静态方法

  Modifier.isAbstract(int modifiers)
    Modifier.isFinal(int modifiers)
    Modifier.isInterface(int modifiers)
    Modifier.isNative(int modifiers)
    Modifier.isPrivate(int modifiers)
    Modifier.isProtected(int modifiers)
    Modifier.isPublic(int modifiers)
    Modifier.isStatic(int modifiers)
    Modifier.isStrict(int modifiers)
    Modifier.isSynchronized(int modifiers)
    Modifier.isTransient(int modifiers)
    Modifier.isVolatile(int modifiers)

Package Info

You can obtain information about the package from a Class object like this:

Class c = new String();
Package package = c.getPackage();

From the Package object you have access to information about the package like its name, specificationVersion,etc…

SuperClass

From the Class object you can access the upserclass of the class. Here is how:

Class superClass = c.getSuperClass();

The superclass class object is a Class object like any other, so you can continue doing class reflection on that too.

Implemented Interfaces

It is possible to get a list of the interfaes implemented by a given class. Here is how:
返回一个被这个类实现的接口列表的类类型。
在java反射中,接口也可以被一个类 类型所表示。

  Class<String> c = String.class;

        Class<?>[] interfaces = c.getInterfaces();
        for (Class<?> anInterface : interfaces) {
            System.out.println(anInterface);
        }

以String 为例,一下是源码和输出。
在这里插入图片描述
再看String类的定义,可以看到实现的接口与输出一致。
在这里插入图片描述

Constructors

You can access the constructors of a class like this;

Constructor[] constructors = c.getConstructors();

以下是代码和输出内容:
在这里插入图片描述

Obtaining Constructor Obejcts

The Constructor class is obtained from the Class object. Here is an example

Class c = String.class;
Constructor[] constructors = c.getConstructors();

The **Constructor[] ** array will have one Constructor instance for each public constructor declared in the class.

If you know the precise paramter types of the constructor you want to access, you can do so rather than obtain the array all constructors.

Class c = String.class;
Constructor constructor = c.getConstructors(String.class);

If no constructor matches the given constructor arguments, a NoSuchMethodException is thrown

Constructor Parameters

You can read what parameters a given constructor takes like this:

Constructor constructor =c.getConstructors(String.class);
Class[] parameterTypes = constructor.getParameterTypes();

Instantiating Objects using Constructor Object

You can instantiate an object like this;

Constructor constructor =c.getConstructors(String.class);
String str = (String)constructor.newInstance("hello,world");

The Constructor.newInstance() methods takes an optional amount of parameters, but you must supply exactly one parameter per argument in the constructor you are invoking.

Methods

You can access the methods of a class like this:

 Method[] method = c.getMethods();

以下是代码和输出内容

在这里插入代码片
Using Java Reflection you can inspect the methods of classes and invoke them at runtime.

Obtaining Method Objects

The Method class is obtained from the Class object. Here is an example.

Class c = String.class;
Method[] methods = c.getMethods();

The Method[] array will have one Method instance for each public method declared in the class.

If you know the precise parameter types of the method you want to access, you can do so rahter than obtain the array all methods.

Class c = String.class;
Method[] methods = c.getMethod("doSomething",new Class[] {String.class});

If no method matches the given method name and arguments, in this case, String.class, a NoSuchMethodExpcetion is thrown.

There are source code show you the meaning of arguments.
在这里插入图片描述
If the method you are trying to access takes no paramenters, pass null as the parameter type array, like this:

Class c = String.class;
Method method = c.getMethod("doSomething",null);

Method Parameters and Return Types

You can read what parameters a given method takes like this:

Method method = c.getMethod(String name, Class<?>... parameterTypes);
Class [] parameterTypes = method.getParameterTypes();

You can access the return type of a method like this:

Class returnTyp = method.getReturnType();

Invoking Methods using Method Object

You can invoke a method like this:

//get method that takes a String as argument
Method method = MyObject.class.getMethod("doSomething", String.class);

Object returnValue = method.invoke(null, "parameter-value1");

The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance. In this example, if soSomething(String.class) is not static, you need to supply a valid MyObject instance instead of null;

The Method.invoke(Object target, Object … parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String, so one String must be supplied.

Getters and Setters

Java Reflection allow you to inspect the methods of classes and invoke them at runtime. This can be used to detect what getters and setters a given class has. You cannot ask for getters and stters explicitly, so you will have to scan through all the mthods of a class and check if each method is a getter or setter.

Getter

A getter method have its name start with “get”, take 0 parameters, and return a value.

Setter

A setter method have its name start with “set”, and takes 1 parameter.

Setters may or may not return a value. Some setters return void, some the value set, others the object the setter were called on for use in method chaining. Therefore you should make no assumptions about the return type of a setter.

Here is a code example that finds getter and stters of a class.

package com.practice.methoddemo;

import java.lang.reflect.Method;

/**
 * @Classname MethodDemo03
 * @Description 一个简单的判断是否Getter Setter的Demo
 * @Date 2021/3/15 14:50
 * @Created by YoungLiu
 */
public class MethodDemo03 {
    public static void main(String[] args) {
        Method[] methods = String.class.getMethods();

        for (Method method : methods) {
            if(isGetter(method)){
                System.out.println("getter: " + method);
            }
            if(isSetter(method)){
                System.out.println("setter: "+ method);
            }
        }

    }

    public static boolean isGetter(Method method){
        if(!method.getName().startsWith("get")){
            return false;
        }
        if(method.getParameterTypes().length!=0){
            return false;
        }
        // method.getReturnType 返回 returnType 的 类类型
        if(void.class.equals(method.getReturnType())){
            return false;
        }
        return true;
    }

    public static boolean isSetter(Method method){
        if(!method.getName().startsWith("set")){
            return false;
        }
        if(method.getParameterTypes().length!=1){
            return false;
        }
        return true;
    }
}

Accessing Private Fields and Private Methods

Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection.

Accessing Private Fields

To access a private field you will need to call the Class.getDeclaredField(String name) or Class.getDeclaredFields() method. The methods Class.getField(String name) and Class.getFields() methods only return public fields, so they won’t work. Here is simple example of a class with a private field, and below that the code to access that field via Java Reflection.

/**
 * @Classname MethodDemo04
 * @Description Accessing Private Fields
 * @Date 2021/3/15 15:01
 * @Created by YoungLiu
 */
public class MethodDemo04 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //1.声明了一个拥有私有成员变量的对象
        PrivateObject privateObject = new PrivateObject("The private value");
        //2.使用反射技术来获取指定的私有变量成员,并设置是否可以访问私有变量
        Field privateStringField = PrivateObject.class.getDeclaredField("privateString");
        privateStringField.setAccessible(true);
        
        //3.通过反射,访问私有变量
        String fieldValue = (String)privateStringField.get(privateObject);
        System.out.println("fieldValue = " +fieldValue);
        
    }
}

class PrivateObject{

    private String privateString = null;
    public PrivateObject(String privateString){
        this.privateString = privateString;
    }
}

Notice the use of the method PrivateObject.class.getDeclaredField(“privateString”). It’s this method call that returns the private field. This method only returns fields declared in that particular class, not fields declared in any superclasses.

Notice the line in bold too. By calling Field.setAcessible(true) you turn off the access checks for this particular Field instance, for reflection only. Now you can access it even if it is private, protected or package scope, even if the caller is not part of those scopes. You still can’t access the field using normal code. The compiler won’t allow it.

Accessing Private Methods

To access a private method you will need to call the Class.getDeclaredMethod(String name, Class [] parameterTypes) or **Class.getDeclaredMethods() ** method. The two methods mention above only return public methods, so they won’t work. Here is simple example of a class with a private method, and below that the code to access that method via Java Reflection.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Classname MethodDemo05
 * @Description Accessing Private Method
 * @Date 2021/3/15 15:14
 * @Created by YoungLiu
 */
public class MethodDemo05 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        PrivateObject2 privateObject2 = new PrivateObject2("The Private Value");
        /**
         * Params:
         * name – the name of the method
         * parameterTypes – the parameter array
         */
        Method privateString2Method = PrivateObject2.class.getDeclaredMethod("getPrivateString2", null);
        //turn off access checks
        privateString2Method.setAccessible(true);
        //invoke the method
        /**
         * Params:
         * obj – the object the underlying method is invoked from
         * args – the arguments used for the method call
         */
        String returnValue =(String)privateString2Method.invoke(privateObject2,null);
        System.out.println(returnValue);

    }
}
class PrivateObject2{

    private String privateString2 = null;

    public  PrivateObject2(String privateString2){
        this.privateString2=privateString2;
    }

    private String getPrivateString2(){
        return this.privateString2;
    }
}

Notice the use of the method PrivateObject.class.getDeclaredMethod(“privateString”). It’s this method call that returns the private method. This method only returns methods declared in that particular class, not methods declared in any superclass.

Also by calling Method.setAccessible(true) you turn off the access checks for this particular Method instance, for reflection only.

Fields

You can access the fields (member variables) of a class like this:

 Field[] method = c.getFields();

Using Java Reflection you can insepct the fields(member variables) of classes and get/set them at runtime. This is done via the Java class java.lang.reflect.Field

Obtaining Field Objects

 Class c = String.class;
 Field[] method = c.getFields();

The Field[] array wil have one Field instance for each public field declared in the class.

If you know the name of the field you want to access, you can access it like this:

//获得一个准确的成员变量(member variables)
Field field = c.getField("someField");

//这是成员变量的定义
public class MyObject{
	public String someField = null;
}

如果找不到执行的成员变量,会抛出 NoSuchFieldException

Field Name

Once you have obtained a Field instance, you can get its field name using the Field.getName() method, like this:

Field field = c.getField("someField");
String fieldName = field.getName();

Field Type

You can determine the field type(String, int etc…) of a field using Field.getType() method.

Field field = c.getField("SomeField");
Object fieldType = field.getType():

在这里插入图片描述

Getting and Setting Field Values

Once you have obtained a Field reference you can get and set its values using the Field.get() and Field.set() methods, like this:

public class ClassDemo07 {
    public static void main(java.lang.String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class<MyObject> c = MyObject.class;


        Field field = c.getField("str");
        System.out.println(field.getType());

        MyObject myObjectInstance = new MyObject();

        Object value= field.get(myObjectInstance );
        field.set(myObject,value);
        System.out.println(field);
    }
}
class MyObject{
    public static java.lang.String str = "123";

}

The myObjectInstance parameter passed to the get and set method should be an instance of the class that owns the field. In the above example an instance of MyObject is used, because the str is an instance member of the MyObject class.

If the field is a static field(public static …) pass null as parameter to the get and set methods, instead of the myObjectInstance parameter passed above.

Generics

People often said that all Java Generics information is erased at compile time so that you cannot access any of that information at runtime. This is not entirely true enough. It’s possible to access generics information at runtimein a handful of cases. These cases actually cover several of our needs for Java Generics information.

The Generics Reflection Rule of Thumb

Using Java Generics typically falls into one of two different situations:

  1. Declaring a class/interface as being parameterizable
  2. Using a parameterizable class

When you wirte a class or interface you can specify that it should be paramerizable. This is the case with the java.util.List interface. Rahter than create a list of Object you can parameterize java.util.List to create a list of say String, like this:

List<String> myList = new ArrayList<String>();

When inspecting a parameterizable type itself at runtime via reflection, like java.util.List , there is no way of knowing what type is has been parameterized to. The object itself does not know what it was parameterized to.

However, the reference to the object knows what type including generic type it is referencing. That is, if it is not a local variable. If an object is referenced by a field in an object, then you can look at the Field declaration via reflection, to obtain information about the generic type declared by that field.

The same is possible if the object is referenced by a parameter in a method. Via the Parameter object for that method (a Java reflection object) you can see what generic type that parameter is declared to.

Finally, you can also look at the return type of a method to see that generic type it is declared to. Again, you cannot see it from the actual object returnd. You need to look at the method declaration via reflection to see what return type (including generic type) it declares.

To sum it up: You can only see from the declarations of references (fields, parameters, return types) what generic type of an object referenced by these references would have. You cannot see it from the object itself.

Generic Method Return Types

If you have obtained a java.lang.reflect.Method object it is possible to obtain information about its generic return type. Here is the code.


/**
 * @Classname GnericDemo1
 * @Description simple example for get generic information via Java Reflection
 * @Date 2021/3/15 16:25
 * @Created by YoungLiu
 */
public class GnericDemo1 {

    protected List<String> stringList = new LinkedList<>();

    public List<String> getStringList(){
        return this.stringList;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Method method = GnericDemo1.class.getMethod("getStringList", null);

        Type returnType = method.getGenericReturnType();

        // about instanceof keyword see more detail at this website:
        // https://armedia.com/blog/instanceof-avoid-in-code/
        if(returnType instanceof ParameterizedType){
            ParameterizedType type = (ParameterizedType) returnType;
            Type[] typeArguments = type.getActualTypeArguments();
            for (Type typeArgument : typeArguments) {
                Class typeArgClass = (Class)typeArgument;
                System.out.println("typeArgClass = " +typeArgClass);
            }
        }
    }
}

This piece of code will print out the text “typeArgClass = java.lang.String”. The Type[] array typeArguments array will contain one item - a Class instance representing the class java.lang.String.Class implement the Type interface.

Generic Method Parameter Types

You can also access the generic types of parameter types at runtime via Java Reflection. Here is the code that with an class have a method taking a parameterized List as parameter.


import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @Classname GenericDemo02
 * @Description this demo shows how to get generic information in method parameter.
 * @Date 2021/3/15 16:37
 * @Created by YoungLiu
 */
public class GenericDemo02 {

    protected List<String> list;

    public void setStringList(List<String> list){
        this.list = list;
    }

    public static void main(String[] args) throws NoSuchMethodException {

        Method method = GenericDemo02.class.getMethod("setStringList", List.class);
        //method.getGenericParameterTypes():
        //Returns an array of Type objects that represent the formal parameter types
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        //To get each one parameter type.
        for (Type genericParameterType : genericParameterTypes) {
            //ParameterizedType represents a parameterized type such as Collection<String>.
            // to see if  genericParameterType is ParameterizedType
            if(genericParameterType instanceof ParameterizedType){
                //upcast
                ParameterizedType type = (ParameterizedType) genericParameterType;
                // an array of Type objects representing the actual type arguments to this type
                Type[] actualTypeArguments = type.getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    //To get actual Class class of type
                    Class parameterArgClass = (Class) actualTypeArgument;
                    System.out.println("parameterArgClass = "+parameterArgClass);
                }
            }
        }
    }
}

This code will print out the text “parameterArgType = java.lang.String”. The Type[] array parameterArgTypes array will contain one item - a Class instance representing the class java.lang.String. Class implements the Type interface.

Generic Field Types

It is also possible to access the generic types of public fields. Fields are class member variables - either static or instance variables.

/**
 * @Classname GenericDemo03
 * @Description this demo show how to use Field for getting generic information.
 * @Date 2021/3/15 16:50
 * @Created by YoungLiu
 */
public class GenericDemo03 {
    public List<String> list ;

    public static void main(String[] args) throws NoSuchFieldException {
        Field field = GenericDemo03.class.getField("list");

        /**
         * Returns:
         * a Type object that represents the declared type for
         * the field represented by this Field object
         */
        Type genericType = field.getGenericType();

        if(genericType instanceof ParameterizedType){
            ParameterizedType type = (ParameterizedType) genericType;
            Type[] fieldArgTypes  = type.getActualTypeArguments();
            for (Type fieldArgType : fieldArgTypes) {
                Class fieldArgClass = (Class)fieldArgType;
                System.out.println("fieldArgClass = " + fieldArgClass);
            }
        }
    }
}

This code will print out the text “fieldArgClass = java.lang.String”

Arrays

Working with arrays via Java Reflection is done using the Java.lang.reflect.Array class. Do not confuse this with Java.util.Arrays class in the Java Collections suite.

Creating arrays via Java Reflection is done using the java.lang.reflect.Array class. Here is the code.

int [] intArray = (int [] ) Array.newIntance(int.class,3);

This code sample creates an array of int. The first parameter int.class given to the Array.newInstance() method tells what type each element in the array should be of. The second parameter states how many elements the array shouble have space of.

/**
 * @Classname ArrayDemo01
 * @Description show basic useage of java.lang.reflect.Array
 * @Date 2021/3/15 17:07
 * @Created by YoungLiu
 */
public class ArrayDemo01 {
    public static void main(String[] args) {
        int [] intArray = (int []) Array.newInstance(int.class,3);
        Array.set(intArray,0,123);
        Array.set(intArray,1,456);
        Array.set(intArray,2,789);

        System.out.println("intArray[0] =" + Array.get(intArray,0));
        System.out.println("intArray[1] =" + Array.get(intArray,1));
        System.out.println("intArray[2] =" + Array.get(intArray,2));
    }
}

/**
This code sample will print out this;
intArray[0] =123
intArray[1] =456
intArray[2] =789

*/


Obtaining the Class Object of an Array

you can access the primitive int array class object like this.

Class intArray = Class.forName("[I");

The JVM represents an int via the letter I. The [ on the left means it is the class of an int array I am interested in. This works for all other primitives too.

For objects you need to use a slightly different notation:

Class stringArrayClass = Class.forName("[Ljava.lang.String;");

Notice the [L to the left of the class name, and the ; to the right. This means an array of objects with the given type.

As a side note, you cannot obtain the class object of primitives using Class.forName(). Both of the examples below result in a ClassNotFoundException

Class intClass1 = Class.forName("I");
Class intClass2 = Class.forName("int");

There are good praticing way to obtain the class name for primitives as well as objects.

public Class getClass(String className){
  if("int" .equals(className)) return int .class;
  if("long".equals(className)) return long.class;
  ...
  return Class.forName(className);
}

Once you have obtained the Class object of a type there is a simple way to obtain the Class of an array of that type. The solution, or workaround as you might call it, is to create an empty array of the desired type and obtain the class object from that empty array. It’s a bit of a cheat, but it works.

// To get the Class class
Class theClass = getClass(theClassName);
// To get the class of an array of a Class 
Class stringArrayClass = Array.newInstance(theClass, 0).getClass();

This present a single, uniform method to access the array class of arrays of any type. No fiddling with class names etc.

To make sure that the Class object really is an array, you can call the Class.isArray() method to check.

Class stringArrayClass = Array.newInstance(String.class,0).getClass();
System.out.println("is array: "+ stringArrayClass.isArray() );

Obtaining the Component Type of an Array

Once you have obtained the Class object for an array you can access its component type via the Class.getComponentType() method. The component type is the type of the items in the array. For instance, the component type of an int[] array is the int.class Classs object. The component type of a String[] array is the java.lang.String Class object.

Here is an example of accessing the component type array:

String [] strings = new String[3];
Class stringArrayClass = strings.getClass();
Class stringArrayComponentType = stringArrayClass.getComponentType();
System.out.println(stringArrayComponentType);

This example will print out the text “java.lang.String” which is the component type of the String array.

Dynamic Proxies

Using Java Reflection you create dynamic implementations of interfaces at rumtime. You do so using the class java.lang.reflect.Proxy. The name of this class is why I refer to these dynamic interface implementations as dynamic proxies. Dynamic interface implementations as dynamic proxies. Dynamic proxies can be used for many different purposes, e.g. database connection and transaction management, dynamic mock object for unit testing, and other AOP-like method intercepting purposes.

Creating Proxies

You create dynamic proxies using the Proxy.newProxyInstance() method. The newProxyInstance() ntedgis taje 3 parameters:

  1. The ClassLoader that is to “load” the dynamic proxy class.
  2. An array of interfaces to implement.
  3. An InvocationHandler to forward all methods calls on the proxy to.

Here is the code:

InvocationHandler handler = new MyInvocationHandler();
MyInterface proxy  = (MyInterface)Proxy.newProxyInstance(
								MyInterface.class.getClassLoader(),
								new Class[] {MyInterface.classs},handler
										);

After running this code the proxy variable caontains a dynamic implementation of the MyInterface interface. All calls to the proxy will be forwarded to the handler implementation of the general InvocationHandler interface.

InvocationHandler’s

As mentioned earlier you must pass an InvocationHandler implementation to the Proxy.newProxyInstance() method. All method calls to the dynamic proxy are forwarded to this InvocationHandler implementation. Here is how the InvocationHanlder interface looks.

public interface InvocationHanlder{
	Object invoke(Object proxy, Method method, Object[] args)throws Throwable;
}

The proxy parameter passed to the invoke() method is the dynamic proxy object implementing the interface. Most often you don’t need this object.

The Mehod object passed into the invoke() method represents the method called on the interface the dynamic proxy implements. From the Method object you can obtain the method name, parameter types, return type, etc.

The Object[] args array contains the parameter values passed to the proxy when the method in the interface implemented was called. Primitives(int, long etc) in the implemented interface are wrapped in their object counterparts(Integer, Long etc.)

Known Use Cases

Dynamic proxies are known to be used for at least the following purposes:

  1. Database Connection and Transaction Management
  2. Dynamic Mock Objects for Unit Testing
  3. Adaptation of DI Container to Custom Factory Interfaces
  4. AOP-like Method Interception

Dynamic Class Loading and Reloading

It is possible to load and reload classed at runtime in Java, though it is not as straightforward as one might have hoped. This text will explain when and how you can load and reload classes in Java.

The ClassLoader

All classes in a Java application are loaded using some subclass of java.lang.ClassLoader. Loading classes dynamically must therefore also be done using a java.lang.ClassLoader subclass.

When a class is loaded, all classes it references are loaded too. This class loading pattern happens recursively, until all classes needed are loaded. This may not be all classes in the application. Unreferenced classed are not loaded until the time they are referenced.

The ClassLoader Hierarchy

Class loaders in Java are organized into a hierachy. When you create a new standard Java ClassLoader you must provide it with a parent ClassLoader. If a ClassLoader is asked to load a class, it will ask its parent class loader to load it. If the parent class loader can’t find the class, the child class loader then tries to load it itself.

Class Loading

The steps a given class loader uses when loading classes are:

  1. Check if the class was already loaded.
  2. If not loaded, ask parent class loader to load the class.
  3. If parent class loader cannot load class, attempt to load it in this class loader.

When you implement a class loader that is capable of reloading classes you will need to deviate a bit from this sequence. The classes to reload should not be requested loaded by the parent class loader.

Dynamic Class Loading

Loading a class dynamically is easy. All you need to do it to obtain a ClassLoader and call its loadClass() method. Here is the code:

/**
 * @Auther: youngLiu
 * @Date: 2021/3/16 09:26
 * @Description: simple demo to show how to dynamic load class
 */
public class MainClass {
    public static void main(String[] args) {
        ClassLoader classLoader = MainClass.class.getClassLoader();

        try {
            Class<?> c = classLoader.loadClass("com.practice.classdemo.ClassUtil");
            System.out.println(c.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Dynamic Class Reloading

Dynamic class reloading is a bit more challenging. Java’s builtin Class loaders always checks if a class is already before loading it.Reloading the class is therefore not possible using Java’s builtin class loaders. To reload a class you will have to implement your own ClassLoader subclass.

Designing your Code for Class Reloading

to be continued…

Modules

This text will explain how to access the Java Module a Java class belongs to via Java reflection.The concept of Java modules was added to Java 9 with the Java Platform Module System. A Java module is a set of Java packages. Thus, each Java class belongs to a package, and the package belongs to a module.
Java 9 的新特性,觉得暂时还用不上,以后再回看。。。

Annotations

You can access the class annotations of a class liek this;

 Annotation[] annotations = c.getAnnotations();

What are Java Annotations?

Annotations is a new feature from Java 5. Annotations are a kind of comment or meta data you can insert in your Java code. These annotations can then be processed at compile time by pre-compiler tools, or at runtime via Java Reflection.
Here is an simple sample of class annotation.

@MyAnnotation(name"someName", value ="Hello world")
public class TheClass{
}

The class TheClass has the annotation @MyAnnotation written ontop. Annotations are defined like interfaces. Here is the MyAnnotation definition:

@Rentention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)

public @interface MyAnnotation{
	public String name();
	public String value();
}

The @ in front of the interface marks it as an annotation. Once you have defined the annotation you can use it in your code.

The two directives in the annotation definition @Retention(RetentionPolicy.RUNTIME) and
@Target(ElementType.TYPE) specifies how the annotation is to be used.

@Retention(RetentionPolicy.RUNTIME) means that the annotation can be accessed via reflection at runtime. If you do not set this directive, the annotation will not be preserved at runtime, and thus not available via reflection.

@Target(ElementType.TYPE) means that the annotation can only be used ontop of types (classes and interfaces typically). You can also specify METHOD or FIELD , or you can leave the target out alltogether so the annotation can be used for both classes, methods and fields.

Class Annotations

when I have learned Java Annoations, will go back here to complete rest of it. to be continues…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值