Java 类之 java.lang.reflect.Method

Java 类之 java.lang.reflect.Method

关联文章:《Java反射详解》https://blog.csdn.net/qq_29689343/article/details/97639037

一、概述

1、java.lang.Class 类获取方法的方法

获取全部公有方法(含继承的,不含私有的)

  1. getMethod(String name, Class<?>... parameterTypes)
    • 获取指定名称和参数类型的公有方法。
    • 如果方法不存在,则抛出 NoSuchMethodException 异常。
  2. getMethods()
    • 获取该类及其父类中所有公有方法的数组。
    • 返回一个 Method 对象数组。

获取本类的所有方法(不含继承的,含私有的)

  1. getDeclaredMethod(String name, Class<?>... parameterTypes)
    • 获取指定名称和参数类型的任意访问权限的方法,包括私有方法。
    • 如果方法不存在,则抛出 NoSuchMethodException 异常。
  2. getDeclaredMethods()
    • 获取该类中所有声明的方法,包括私有方法。
    • 返回一个 Method 对象数组。

代码示例

// 获取公有方法(含继承的,不含私有的)
Method publicMethod = MyClass.class.getMethod("publicMethodName", String.class);

// 获取所有公有方法(含继承的,不含私有的)
Method[] publicMethods = MyClass.class.getMethods();

// 获取本类的私有方法(不含继承的,含私有的)
Method privateMethod = MyClass.class.getDeclaredMethod("privateMethodName", String.class);

// 获取本类的所有方法(不含继承的,含私有的)
Method[] allMethods = MyClass.class.getDeclaredMethods();

2、java.lang.reflect.Method 类简介

java.lang.reflect.Method 类是 Java 反射机制中的一部分,用于表示类的方法。反射是一种在运行时检查或修改类的行为的能力。Method 类提供了对类的方法的信息的访问和操作

3、类定义信息

public final class Method extends Executable

二、基本功能

1、基本功能

  1. 获取方法信息: Method 类允许你获取关于方法的各种信息,如方法名、返回类型、参数类型等。
  2. 调用方法: 你可以使用 invoke 方法动态地调用类的方法,即使在编译时并不知道方法的具体存在。
  3. 获取修饰符: 通过 getModifiers 方法,你可以获取方法的修饰符,如 publicprivatestatic 等。
  4. 获取注解: 使用 getAnnotation 方法,你可以获取方法上指定类型的注解

2、代码示例

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MethodExample {

    public static void main(String[] args) throws Exception {
        // 获取 String 类的所有方法
        Method[] methods = String.class.getMethods();

        // 遍历方法数组
        for (Method method : methods) {
            // 获取方法名
            String methodName = method.getName();
            System.out.println("Method Name: " + methodName);

            // 获取返回类型
            Class<?> returnType = method.getReturnType();
            System.out.println("Return Type: " + returnType.getSimpleName());

            // 获取参数类型
            Class<?>[] parameterTypes = method.getParameterTypes();
            System.out.print("Parameter Types: ");
            for (Class<?> paramType : parameterTypes) {
                System.out.print(paramType.getSimpleName() + " ");
            }
            System.out.println();

            // 获取修饰符
            int modifiers = method.getModifiers();
            System.out.println("Modifiers: " + Modifier.toString(modifiers));

            // 获取注解
            if (method.isAnnotationPresent(Deprecated.class)) {
                System.out.println("Method is Deprecated!");
            }

            System.out.println("---------------------------------------------");
        }

        // 调用 String 类的 length 方法
        Method lengthMethod = String.class.getMethod("length");
        String str = "Hello, World!";
        int length = (int) lengthMethod.invoke(str);
        System.out.println("Length of the string: " + length);
    }
}

三、扩展

1、关于注解的方法

  1. getAnnotation(Class annotationClass):
    • 用途:获取指定类型的注解。
    • 参数:annotationClass - 要获取的注解的 Class 对象。
    • 返回值:指定类型的注解对象,如果该方法没有找到注解,则返回 null。
  2. getAnnotations():
    • 用途:获取该方法上的所有注解。
    • 返回值:一个包含此元素上存在的所有注解的数组。
  3. getDeclaredAnnotation(Class annotationClass):
    • 用途:获取直接存在于此元素上的、指定类型的注解。
    • 参数:annotationClass - 要获取的注解的 Class 对象。
    • 返回值:指定类型的注解对象,如果该方法没有找到注解,则返回 null。
  4. getDeclaredAnnotations():
    • 用途:获取直接存在于此元素上的所有注解。
    • 返回值:一个包含此元素上存在的所有注解的数组。
  5. isAnnotationPresent(Class<? extends Annotation> annotationClass):
    • 用途:判断指定类型的注解是否存在于该元素上。
    • 参数:annotationClass - 要检查的注解的 Class 对象。
    • 返回值:如果指定类型的注解存在于此元素上,则返回 true;否则返回 false。

2、getAnnotations()getDeclaredAnnotations()的区别

区别

getAnnotations()getDeclaredAnnotations()java.lang.reflect.Method 类中用于获取方法上注解的两个方法,它们之间存在一些区别:

  1. 范围:
    • getAnnotations(): 返回此元素上存在的所有注解,包括从父类、接口继承而来的注解
    • getDeclaredAnnotations(): 返回直接存在于此元素上的所有注解,不包括继承而来的注解
  2. 继承:
    • getAnnotations(): 包括继承而来的注解,即如果该方法在父类或接口中有注解,也会被返回。
    • getDeclaredAnnotations(): 只返回直接在当前方法上声明的注解,不包括继承而来的注解
  3. 可见性:
    • getAnnotations(): 返回的注解包括所有可见的注解,无论其访问级别是 publicprotecteddefault 还是 private
    • getDeclaredAnnotations(): 只返回当前方法上直接声明的注解,与其可见性无关。

代码示例

仅作参考!

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationExample {

    @CustomAnnotation
    public void annotatedMethod() {
        // Method with annotation
    }

    public static void main(String[] args) throws NoSuchMethodException {
        Class<?> clazz = AnnotationExample.class;
        Method method = clazz.getMethod("annotatedMethod");

        // getAnnotations() - 包括继承而来的注解
        Annotation[] annotations = method.getAnnotations();
        System.out.println("getAnnotations() - Total Annotations: " + annotations.length);

        // getDeclaredAnnotations() - 只返回直接声明的注解
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        System.out.println("getDeclaredAnnotations() - Total Annotations: " + declaredAnnotations.length);
    }
}

// Custom Annotation
@interface CustomAnnotation {
}

3、invoke 方法

简介

invoke 方法是 java.lang.reflect.Method 类中的一个重要方法,用于在运行时动态地调用方法。该方法允许你通过反射机制调用指定对象的特定方法,即使在编译时你可能不知道这个方法的具体存在。

方法签名

public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException

参数说明

  • obj:要调用方法的对象。如果方法是静态的,则可以将 obj 参数设置为 null
  • args:要传递给方法的参数数组

异常

  • IllegalAccessException:如果底层方法是私有的、受保护的或者包访问级别,并且无法访问。
  • IllegalArgumentException:如果提供的参数不匹配方法的参数。
  • InvocationTargetException:如果底层方法抛出异常,则包装在 InvocationTargetException 中。

代码示例

import java.lang.reflect.Method;

public class InvokeExample {

    public static void main(String[] args) throws Exception {
        // 获取 String 类的 length 方法
        Method lengthMethod = String.class.getMethod("length");

        // 创建一个字符串对象
        String str = "Hello, World!";

        // 调用 length 方法
        int length = (int) lengthMethod.invoke(str);

        System.out.println("Length of the string: " + length);
    }
}

4、是否支持修改方法

在 Java 中,通过反射机制可以在运行时获取和调用方法,但并不直接支持对方法的修改。反射主要用于获取关于类和方法的信息,以及在运行时动态调用方法,而不是用于修改类的结构

方法的修改通常是在编译时完成的,而不是在运行时。在 Java 中,类一旦加载就被认为是不可修改的(除非使用特殊的技术,如字节码增强库,但这并不是标准的 Java 功能)。

如果你想要修改类的行为,你可能需要考虑其他方式,如使用代理模式、AOP(面向切面编程)或字节码操作库,例如 ASM 或 Byte Buddy。这些方法允许你在运行时对类的行为进行一些定制,但也需要小心使用,以避免不稳定和难以维护的代码。

总体而言,Java 的设计哲学是在编译时进行尽可能多的检查和优化,以提高代码的性能和可靠性。因此,动态修改类的结构并不是 Java 语言的主要特性,而是通过其他手段来实现。

5、其它注意点

  1. 异常处理: 使用 invoke 方法时,需要注意处理可能抛出的异常,包括 IllegalAccessExceptionIllegalArgumentExceptionInvocationTargetException。这些异常可能在调用方法时发生,因此需要进行适当的异常处理。

    try {
        // 调用方法的代码
    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        // 处理异常的代码
    }
    
  2. 可访问性: 如果调用的方法是私有的、受保护的或者包访问级别的,需要通过 setAccessible(true) 方法设置方法为可访问,否则会抛出 IllegalAccessException 异常。

    method.setAccessible(true);
    

    注意:在访问私有方法时,这可能会涉及到安全性和代码规范的问题,应该慎重使用。

  3. 方法参数和返回值: 在调用方法时,需要确保传递的参数类型和个数与方法的参数匹配,并且要注意类型转换。同样,需要根据方法的返回类型进行适当的类型转换。

    // 获取方法的参数类型
    Class<?>[] parameterTypes = method.getParameterTypes();
    
    // 检查参数是否匹配,然后调用方法
    if (parameterTypes.length == args.length) {
        method.invoke(obj, args);
    }
    
  4. 性能影响: 反射操作相对于直接调用方法会有一些性能开销,因此在高性能要求的情况下,应谨慎使用反射。如果可能,可以考虑使用直接的方法调用来提高性能。

  5. 泛型处理: 如果方法使用了泛型,需要注意处理泛型类型擦除的情况。在获取方法的参数类型或返回类型时,可能需要使用 getGenericParameterTypesgetGenericReturnType 来获取泛型信息。

    java.lang.reflect.Type[] genericParameterTypes = method.getGenericParameterTypes();
    java.lang.reflect.Type genericReturnType = method.getGenericReturnType();
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具 * * * Description: 将大部分的数据库操作放入这个中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值