利用反射分析类的能力

本文通过实例演示了如何使用Java反射API获取类的全部域、构造器和方法,包括访问修饰符、参数类型和返回类型。同时展示了如何利用反射进行类的动态操作,如调用方法、比较double值等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

getDeclaredFields()

返回类的全部域

getDeclaredConstructors()

返回类的所有构造器

getDeclaredMethods()

返回类的全部方法,不包括从父类继承来的

getModifiers()

返回修饰符

getParameterTypes()

获取参数类型

getReturnType()

获取返回类型

package com.java.reflectdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;

/**
 * 打印一个类的全部信息
 */
public class ReflectionTest {

    public static void main(String[] args) {
        String name;
        if (args.length > 0) {
            name = args[0];
        } else {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Please enter class name(e.g.  java.util.Date):");
            name = scanner.nextLine();
        }

        // public class java.lang.Double extends java.lang.Number
        try {
            Class cl = Class.forName(name);
            Class superCl = cl.getSuperclass();

            String modifiers = Modifier.toString(cl.getModifiers());
            if (modifiers.length() > 0)
                System.out.print(modifiers + " "); // public
            System.out.print("class " + name); // class java.lang.Double

            // 显示继承父类的信息
            if (superCl != null && superCl != Object.class) {
                System.out.print(" extends " + superCl.getName());
            }

            // 显示构造器、域、方法
            System.out.print("\n{\n");
            printConstructors(cl);
            System.out.println();
            printMethods(cl);
            System.out.println();
            printFields(cl);
            System.out.println("}");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /*
        构造器
     */
    public static void printConstructors(Class cl) {

        // getDeclaredConstructors 返回全部构造器
        Constructor[] constructors = cl.getDeclaredConstructors();

        // public java.lang.Double(java.lang.String);
        for (Constructor constructor : constructors) {
            String name = constructor.getName();
            System.out.print("      ");
            // getModifiers 修饰符
            String modifiers = Modifier.toString(constructor.getModifiers());
            if (modifiers.length() > 0)
                System.out.print(modifiers + " ");  // "public "
            System.out.print(name + "("); // "java.lang.Double("

            // getParameterTypes  构造方法参数
            Class[] paramTypes = constructor.getParameterTypes();
            for (int j = 0; j < paramTypes.length; j++) {
                if (j > 0)
                    System.out.print(",");
                System.out.print(paramTypes[j].getName()); // java.lang.String
            }
            System.out.println(");"); // ");"
        }

    }

    /*
        方法    public static java.lang.Double valueOf(java.lang.String);
     */
    public static void printMethods(Class cl) {

        // getMethods 返回全部方法
        Method[] methods = cl.getDeclaredMethods();

        for (Method method : methods) {
            Class retType = method.getReturnType(); // 返回类型  java.lang.Double
            String name = method.getName(); // 方法名  valueOf

            System.out.print("      ");
            String modifiers = Modifier.toString(method.getModifiers()); // public static 修饰符
            if (modifiers.length() > 0)
                System.out.print(modifiers + " ");  // "public static "
            System.out.print(retType.getName() + " " + name + "("); // "java.lang.Double valueOf("

            Class[] paramTypes = method.getParameterTypes();
            for (int j = 0; j < paramTypes.length; j++) {
                if (j > 0)
                    System.out.print(",");
            }
            System.out.println(");");
        }

    }

    /*
        域      public static final double POSITIVE_INFINITY;
     */
    public static void printFields(Class cl) {

        // getDeclaredFields  返回域
        Field[] fields = cl.getDeclaredFields();

        for (Field field : fields) {
            Class type = field.getType(); // 类型
            String name = field.getName();

            System.out.print("      ");
            String modifiers = Modifier.toString(field.getModifiers());
            if (modifiers.length() > 0)
                System.out.print(modifiers + " ");  // "public static final "
            System.out.println(type.getName() + " " + name + ";"); // "double POSITIVE_INFINITY;"
        }

    }

}

 

运行结果:

Please enter class name(e.g.  java.util.Date):
java.lang.Double
public final class java.lang.Double extends java.lang.Number
{
      public java.lang.Double(double);
      public java.lang.Double(java.lang.String);

      public boolean equals();
      public static java.lang.String toString();
      public java.lang.String toString();
      public int hashCode();
      public static int hashCode();
      public static double min(,);
      public static double max(,);
      public static native long doubleToRawLongBits();
      public static long doubleToLongBits();
      public static native double longBitsToDouble();
      public volatile int compareTo();
      public int compareTo();
      public byte byteValue();
      public short shortValue();
      public int intValue();
      public long longValue();
      public float floatValue();
      public double doubleValue();
      public static java.lang.Double valueOf();
      public static java.lang.Double valueOf();
      public static java.lang.String toHexString();
      public static int compare(,);
      public static boolean isNaN();
      public boolean isNaN();
      public static boolean isFinite();
      public static boolean isInfinite();
      public boolean isInfinite();
      public static double sum(,);
      public static double parseDouble();
      public final void wait();
      public final void wait(,);
      public final native void wait();
      public final native java.lang.Class getClass();
      public final native void notify();
      public final native void notifyAll();

      public static final double POSITIVE_INFINITY;
      public static final double NEGATIVE_INFINITY;
      public static final double NaN;
      public static final double MAX_VALUE;
      public static final double MIN_NORMAL;
      public static final double MIN_VALUE;
      public static final int MAX_EXPONENT;
      public static final int MIN_EXPONENT;
      public static final int SIZE;
      public static final int BYTES;
      public static final java.lang.Class TYPE;
      private final double value;
      private static final long serialVersionUID;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值