1. ホーム
  2. java

[解決済み] リフレクションを使ってメソッドが静的であるかどうかを確認するにはどうすればよいですか?

2022-10-30 01:45:19

質問

あるクラスの静的メソッドのみを実行時に検出したいのですが、どのようにすればよいのでしょうか。 または、静的メソッドと非静的メソッドを区別する方法。

どのように解決するのですか?

使用方法 Modifier.isStatic(method.getModifiers()) .

/**
 * Returns the public static methods of a class or interface,
 *   including those declared in super classes and interfaces.
 */
public static List<Method> getStaticMethods(Class<?> clazz) {
    List<Method> methods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        if (Modifier.isStatic(method.getModifiers())) {
            methods.add(method);
        }
    }
    return Collections.unmodifiableList(methods);
}

注意:このメソッドはセキュリティの観点からすると実は危険です。Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (Java secure coding guidelinesのセクション6を参照してください).

免責事項: テストしていませんし、コンパイルすらしていません。

備考 Modifier は注意して使用する必要があります。intとして表されるフラグは型安全ではありません。よくある間違いは、適用されないReflectionオブジェクトのタイプで 修飾フラグをテストすることです。同じ位置のフラグが他の情報を示すために設定されていることがあります。