13:反射

1:概念:在运行状态中,对于任何一个类,我们可以获取它的属性和方法,对于这种动态获取对象信息和方法的机制,我们称为反射机制。

2:优点:可以在程序中访问已经加载到JVM中的Java对象的描述,实现访问,检测和修改描述Java对象本身信息的功能。

package FanShe;

import javax.swing.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射,及常用方法
 */
public class JavaFanShe {
    public static void main(String[] args) {
        JTextField textField = new JTextField();
        Class textFileC = textField.getClass();
        Package textFileCPackage = textFileC.getPackage();
        String textFileCName = textFileC.getName();
        Class textFileCSuperclass = textFileC.getSuperclass();
        Class[] textFileCInterfaces = textFileC.getInterfaces();
        Constructor[] textFileCConstructors = textFileC.getConstructors();
        for(int i=0;i<textFileCConstructors.length;i++){
            Constructor textFileCConstructor = textFileCConstructors[i];
            System.out.println(textFileCConstructor);
        }
        Constructor[] textFileCDeclaredConstructors = textFileC.getDeclaredConstructors();
        Method[] textFileCMethods = textFileC.getMethods();
        Method[] textFileCDeclaredMethods = textFileC.getDeclaredMethods();
        Field[] textFileCFields = textFileC.getFields();
        Field[] textFileCDeclaredFields = textFileC.getDeclaredFields();
        Class[] textFileCClasses = textFileC.getClasses();
        Class textFileCDeclaringClass = textFileC.getDeclaringClass();
        Class[] textFileCDeclaredClasses = textFileC.getDeclaredClasses();
    }
}

3:Annotation定义与使用:

package FanShe;

/**
 * 定义一个Annotation
 */
public @interface Annotation {
    String name();
    int age() default 12;
    Class type() default void.class;
}


测试类:
package FanShe;

import jdk.nashorn.internal.objects.annotations.Constructor;

public class TestAnnotation {

  @Annotation(name = "张三" , type = String.class)
  public void Annotation(){

  }
}

猜你喜欢

转载自www.cnblogs.com/zwh820672664/p/10835240.html
13
13)