Java : Member with Examples
Member (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Member methods.
Summary
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
Fields
static final int DECLARED
System.out.println(Member.DECLARED); // 1
static final int PUBLIC
System.out.println(Member.PUBLIC); // 0
Methods
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));
}
// Result
// ↓
//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());
}
// Result
// ↓
//public void IsSyntheticTest$Bar.aaa(java.lang.String)
//false
//public void IsSyntheticTest$Bar.aaa(java.lang.Object)
//true
}
}