LoginSignup
1
2

More than 5 years have passed since last update.

[リフレクション]メソッドがstaticかどうかを判定するにはModifier#isStaticを利用する。

Posted at

Javaプログラミングにおいて、少しばかり複雑なことをしようとすると、必ず頭をもたげてくるのがリフレクション。リフレクションを利用し、とあるクラスのメソッド一覧を取得するような処理を書くことは多いと思いますが、その際取得したメソッドがstaticか否かを判定したいという場合にはModifier#isStaticを利用します。以下がそのサンプルとなります。

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


public class StaticTest {

    public static void main(String[] args) {
        Method[] methods = Sample.class.getDeclaredMethods();
        for (Method method : methods) {
            if (Modifier.isStatic(method.getModifiers())) {
                System.out.println(method.getName());
                // => privateStaticMethod publicStaticMethod
            }
        }
    }

    public static final class Sample {
        public static void publicStaticMethod() {};
        private static void privateStaticMethod() {};
        public void publicInstanceMethod(){};
        private void privateInstanceMethod(){};
    }
}

参考: 『Modifier (Java Platform SE 8 )』

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2