Java : Member - API使用例
Member (Java SE 18 & JDK 18) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。
概要
Member は、クラスやインタフェース、列挙型などの
- コンストラクタ
- メソッド
- フィールド
を抽象的に表します。
Member のインスタンスは Class クラスから取得することができます。
public class Foo {
private int num;
public Foo(double d) {
}
public void aaa(String str) {
}
}
final var cls = Foo.class;
final Member constructor = cls.getDeclaredConstructor(double.class);
System.out.println(constructor); // public Foo(double)
final Member method = cls.getDeclaredMethod("aaa", String.class);
System.out.println(method); // public void Foo.aaa(java.lang.String)
final Member field = cls.getDeclaredField("num");
System.out.println(field); // private int Foo.num
フィールド
static final int DECLARED
System.out.println(Member.DECLARED); // 1
static final int PUBLIC
System.out.println(Member.PUBLIC); // 0
メソッド
Class<?> getDeclaringClass ()
class Foo {
private String str;
}
final Member member = Foo.class.getDeclaredField("str");
System.out.println(member); // private java.lang.String Foo.str
System.out.println(member.getDeclaringClass()); // class Foo
int getModifiers ()
class Foo {
public int a;
protected int b;
private int c;
}
final var cls = Foo.class;
for (final Member member : cls.getDeclaredFields()) {
final var mod = member.getModifiers();
System.out.println("name = " + member.getName() + " : mod = " + mod);
System.out.println(" isPublic : " + Modifier.isPublic(mod));
System.out.println(" isProtected : " + Modifier.isProtected(mod));
System.out.println(" isPrivate : " + Modifier.isPrivate(mod));
}
// 結果
// ↓
//name = a : mod = 1
// isPublic : true
// isProtected : false
// isPrivate : false
//name = b : mod = 4
// isPublic : false
// isProtected : true
// isPrivate : false
//name = c : mod = 2
// isPublic : false
// isProtected : false
// isPrivate : true
String getName ()
public class Foo {
private int num;
public Foo(double d) {
}
public void aaa(String str) {
}
}
final var cls = Foo.class;
final Member constructor = cls.getDeclaredConstructor(double.class);
System.out.println(constructor); // public Foo(double)
System.out.println(constructor.getName()); // Foo
final Member method = cls.getDeclaredMethod("aaa", String.class);
System.out.println(method); // public void Foo.aaa(java.lang.String)
System.out.println(method.getName()); // aaa
final Member field = cls.getDeclaredField("num");
System.out.println(field); // private int Foo.num
System.out.println(field.getName()); // num
boolean isSynthetic ()
import java.lang.reflect.Member;
public class IsSyntheticTest {
interface Foo<T> {
void aaa(T value);
}
class Bar implements Foo<String> {
@Override
public void aaa(String value) {
}
}
public static void main(String[] args) {
final var cls = Bar.class;
for (final Member member : cls.getDeclaredMethods()) {
System.out.println(member);
System.out.println(member.isSynthetic());
}
// 結果
// ↓
//public void IsSyntheticTest$Bar.aaa(java.lang.String)
//false
//public void IsSyntheticTest$Bar.aaa(java.lang.Object)
//true
}
}