Java案例怎么获取类的所有方法?

wen java案例 8

本文目录导读:

Java案例怎么获取类的所有方法?

  1. 基础示例:获取类的方法
  2. 完整的功能示例
  3. 常用方法对比
  4. 实用工具类
  5. 重要提示

在Java中获取类的所有方法,主要使用反射(Reflection)机制,以下是几种常见的实现方式:

基础示例:获取类的方法

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class MethodReflectionDemo {
    public static void main(String[] args) {
        // 获取String类的方法
        printAllMethods(String.class);
        // 或者通过对象获取
        String str = "Hello";
        printAllMethods(str.getClass());
    }
    public static void printAllMethods(Class<?> clazz) {
        System.out.println("类名: " + clazz.getName());
        System.out.println("所有公共方法(包括继承的):");
        // getMethods() 获取所有公共方法(包括继承的)
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println("  " + method);
        }
        System.out.println("\n所有声明的方法(不包括继承的):");
        // getDeclaredMethods() 获取所有声明的方法(包括私有、保护、默认)
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println("  " + method);
        }
    }
}

完整的功能示例

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.Arrays;
public class CompleteMethodReflection {
    public static void main(String[] args) {
        // 自定义类示例
        MyClass obj = new MyClass();
        analyzeClass(obj.getClass());
    }
    public static void analyzeClass(Class<?> clazz) {
        System.out.println("=== 类分析方法 ===");
        System.out.println("类: " + clazz.getName());
        System.out.println();
        // 1. 获取所有公共方法(包括继承的)
        System.out.println("--- 所有公共方法(包括继承)---");
        Method[] publicMethods = clazz.getMethods();
        for (Method method : publicMethods) {
            printMethodInfo(method);
        }
        System.out.println("\n--- 所有声明的方法(包括私有)---");
        // 2. 获取所有声明的方法(不包括继承的)
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            printMethodInfo(method);
        }
        // 3. 获取特定方法
        System.out.println("\n--- 获取特定方法 ---");
        try {
            Method specificMethod = clazz.getDeclaredMethod("greet", String.class);
            System.out.println("找到方法: " + specificMethod);
        } catch (NoSuchMethodException e) {
            System.out.println("方法未找到");
        }
        // 4. 获取所有方法名
        System.out.println("\n--- 所有方法名 ---");
        String[] methodNames = getMethodNames(clazz);
        System.out.println("方法列表: " + Arrays.toString(methodNames));
    }
    // 打印方法详细信息
    public static void printMethodInfo(Method method) {
        // 获取修饰符
        int modifiers = method.getModifiers();
        String modifierStr = Modifier.toString(modifiers);
        // 获取返回类型
        Class<?> returnType = method.getReturnType();
        // 获取方法名
        String methodName = method.getName();
        // 获取参数
        Parameter[] parameters = method.getParameters();
        System.out.println(modifierStr + " " + 
                          returnType.getSimpleName() + " " + 
                          methodName + "(");
        for (int i = 0; i < parameters.length; i++) {
            if (i > 0) System.out.print(", ");
            System.out.print(parameters[i].getType().getSimpleName() + 
                           " " + parameters[i].getName());
        }
        System.out.println(")");
        // 获取异常
        Class<?>[] exceptionTypes = method.getExceptionTypes();
        if (exceptionTypes.length > 0) {
            System.out.print("  抛出异常: ");
            for (int i = 0; i < exceptionTypes.length; i++) {
                if (i > 0) System.out.print(", ");
                System.out.print(exceptionTypes[i].getSimpleName());
            }
            System.out.println();
        }
        System.out.println();
    }
    // 获取所有方法名
    public static String[] getMethodNames(Class<?> clazz) {
        Method[] methods = clazz.getDeclaredMethods();
        return Arrays.stream(methods)
                    .map(Method::getName)
                    .toArray(String[]::new);
    }
}
// 测试类
class MyClass {
    private String name;
    public MyClass() {
        this.name = "Default";
    }
    public void greet(String message) {
        System.out.println(message + ", " + name);
    }
    private int calculate(int x, int y) {
        return x + y;
    }
    protected String getInfo() {
        return "Name: " + name;
    }
    public static void printStatic() {
        System.out.println("Static method");
    }
    public void throwsException() throws InterruptedException {
        Thread.sleep(100);
    }
}

常用方法对比

public class MethodComparison {
    public static void main(String[] args) {
        Class<?> clazz = MyClass.class;
        // getMethods() - 获取所有公共方法(包括从父类继承的)
        System.out.println("getMethods():");
        for (Method m : clazz.getMethods()) {
            System.out.println("  " + m.getName() + " (public: " + 
                             Modifier.isPublic(m.getModifiers()) + ")");
        }
        // getDeclaredMethods() - 获取所有声明的方法(不包括继承的)
        System.out.println("\ngetDeclaredMethods():");
        for (Method m : clazz.getDeclaredMethods()) {
            System.out.println("  " + m.getName() + " (public: " + 
                             Modifier.isPublic(m.getModifiers()) + ")");
        }
    }
}

实用工具类

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
public class MethodUtils {
    // 获取所有方法名列表
    public static List<String> getMethodNames(Class<?> clazz) {
        return Arrays.stream(clazz.getDeclaredMethods())
                    .map(Method::getName)
                    .collect(Collectors.toList());
    }
    // 获取公共方法名列表
    public static List<String> getPublicMethodNames(Class<?> clazz) {
        return Arrays.stream(clazz.getMethods())
                    .map(Method::getName)
                    .collect(Collectors.toList());
    }
    // 获取特定修饰符的方法
    public static List<Method> getMethodsByModifier(Class<?> clazz, int modifier) {
        return Arrays.stream(clazz.getDeclaredMethods())
                    .filter(m -> (m.getModifiers() & modifier) != 0)
                    .collect(Collectors.toList());
    }
    // 获取静态方法
    public static List<Method> getStaticMethods(Class<?> clazz) {
        return getMethodsByModifier(clazz, Modifier.STATIC);
    }
    // 获取私有方法
    public static List<Method> getPrivateMethods(Class<?> clazz) {
        return getMethodsByModifier(clazz, Modifier.PRIVATE);
    }
    // 获取指定返回类型的方法
    public static List<Method> getMethodsByReturnType(Class<?> clazz, Class<?> returnType) {
        return Arrays.stream(clazz.getDeclaredMethods())
                    .filter(m -> m.getReturnType().equals(returnType))
                    .collect(Collectors.toList());
    }
    // 获取有参数的方法
    public static List<Method> getMethodsWithParameters(Class<?> clazz) {
        return Arrays.stream(clazz.getDeclaredMethods())
                    .filter(m -> m.getParameterCount() > 0)
                    .collect(Collectors.toList());
    }
    // 使用示例
    public static void main(String[] args) {
        Class<?> clazz = String.class;
        System.out.println("所有方法名: " + getMethodNames(clazz));
        System.out.println("公共方法名: " + getPublicMethodNames(clazz));
        System.out.println("静态方法数: " + getStaticMethods(clazz).size());
        System.out.println("返回String的方法数: " + 
                          getMethodsByReturnType(clazz, String.class).size());
    }
}

重要提示

  1. getMethods() vs getDeclaredMethods()

    • getMethods():只返回公共方法,包括从父类继承的
    • getDeclaredMethods():返回所有声明的方法(public、protected、default、private),但不包括继承的
  2. 性能考虑:反射操作有性能开销,避免在频繁调用的循环中使用

  3. 安全性:访问私有方法需要使用 setAccessible(true)

  4. 泛型:如果方法有泛型类型,可以使用 getGenericParameterTypes()getGenericReturnType()

抱歉,评论功能暂时关闭!