Java : Class - API Examples

Class (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Class methods.


Summary

Instances of the class Class represent classes and interfaces in a running Java application. An enum class and a record class are kinds of class; an annotation interface is a kind of interface.

Class diagram

System.out.println(Object.class); // class java.lang.Object
System.out.println(int.class); // int
System.out.println(String[].class); // class [Ljava.lang.String;

final var str = "abcd";
System.out.println(str.getClass()); // class java.lang.String
class Foo {
    private int value;
    private String str;

    void aaa() {
    }

    void bbb(int x, int y) {
    }
}

final var cls = Foo.class;

System.out.println("name : " + cls.getSimpleName());

System.out.println("-- field --");
for (final var field : cls.getDeclaredFields()) {
    System.out.println(field);
}

System.out.println("-- method --");
for (final var method : cls.getDeclaredMethods()) {
    System.out.println(method);
}

// Result
// ↓
//name : Foo
//-- field --
//private int Foo.value
//private java.lang.String Foo.str
//-- method --
//void Foo.aaa()
//void Foo.bbb(int,int)

Methods

Class<?> arrayType ()

Returns a Class for an array type whose component type is described by this Class.

final var cls = Object.class;

System.out.println(cls.isArray()); // false
System.out.println(cls.getSimpleName()); // Object

System.out.println(cls.arrayType().isArray()); // true
System.out.println(cls.arrayType().getSimpleName()); // Object[]
final int[] array = {1, 2, 3};
System.out.println(Arrays.toString(array)); // [1, 2, 3]

final var cls = array.getClass();

System.out.println(cls.isArray()); // true
System.out.println(cls.getSimpleName()); // int[]

System.out.println(cls.arrayType().isArray()); // true
System.out.println(cls.arrayType().getSimpleName()); // int[][]

<U> Class<? extends U> asSubclass (Class<U> clazz)

Casts this Class object to represent a subclass of the class represented by the specified class object.

class Base {
}

class Sub extends Base {
}

final var cls = Sub.class.asSubclass(Base.class);
System.out.println(cls.getSimpleName()); // Sub

try {
    Base.class.asSubclass(Sub.class);
} catch (ClassCastException e) {
    System.out.println("ClassCastException!");
}

// Result
// ↓
//ClassCastException!

T cast (Object obj)

Casts an object to the class or interface represented by this Class object.

class Base {
}

class Sub extends Base {
}
final Base base = new Sub();

final Sub sub = Sub.class.cast(base);
System.out.println("Cast OK");

// Result
// ↓
//Cast OK
final Base base = new Base();

try {
    final Sub sub = Sub.class.cast(base);
} catch (ClassCastException e) {
    System.out.println("ClassCastException!");
}

// Result
// ↓
//ClassCastException!

Class<?> componentType ()

Returns the component type of this Class, if it describes an array type, or null otherwise.

This method is equivalent to getComponentType().

Optional<ClassDesc> describeConstable ()

Returns a nominal descriptor for this instance, if one can be constructed, or an empty Optional if one cannot be.

final var cls = String.class;
System.out.println(cls.describeConstable()); // Optional[ClassDesc[String]]
final var cls = Object[].class;
System.out.println(cls.describeConstable()); // Optional[ClassDesc[Object[]]]
final var cls = int.class;
System.out.println(cls.describeConstable()); // Optional[PrimitiveClassDesc[int]]

String descriptorString ()

Returns the descriptor string of the entity (class, interface, array class, primitive type, or void) represented by this Class object.

final var cls = String.class;
System.out.println(cls.descriptorString()); // Ljava/lang/String;
final var cls = Object[].class;
System.out.println(cls.descriptorString()); // [Ljava/lang/Object;
System.out.println(byte.class.descriptorString()); // B
System.out.println(int.class.descriptorString()); // I
System.out.println(char.class.descriptorString()); // C
System.out.println(double.class.descriptorString()); // D

boolean desiredAssertionStatus ()

Returns the assertion status that would be assigned to this class if it were to be initialized at the time this method is invoked.

final var cls = Object.class;
System.out.println(cls.desiredAssertionStatus()); // false

static Class<?> forName (Module module, String name)

Returns the Class with the given binary name in the given module.

final var module = String.class.getModule();
System.out.println(module); // module java.base

final var cls = Class.forName(module, "java.lang.String");
System.out.println(cls.getName()); // java.lang.String

static Class<?> forName (String className)

Returns the Class object associated with the class or interface with the given string name.

final var cls = Class.forName("java.lang.String");
System.out.println(cls.getName()); // java.lang.String

static Class<?> forName (String name, boolean initialize, ClassLoader loader)

Returns the Class object associated with the class or interface with the given string name, using the given class loader.

final var cls = Class.forName("java.lang.String", false, getClass().getClassLoader());
System.out.println(cls.getName()); // java.lang.String
class Foo {
    static {
        System.out.println("Initialize!");
    }
}

final var name = Foo.class.getTypeName();
final var loader = getClass().getClassLoader();

System.out.println("-- initialize false --");

final var ret1 = Class.forName(name, false, loader);
System.out.println(ret1.getSimpleName());

System.out.println("-- initialize true --");

final var ret2 = Class.forName(name, true, loader);
System.out.println(ret2.getSimpleName());

// Result
// ↓
//-- initialize false --
//Foo
//-- initialize true --
//Initialize!
//Foo

AnnotatedType[] getAnnotatedInterfaces ()

Returns an array of AnnotatedType objects that represent the use of types to specify superinterfaces of the entity represented by this Class object.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Bar {
}
interface A {
}

class B implements @Foo @Bar A {
}

final var annotatedTypes = B.class.getAnnotatedInterfaces();

for (final var annotatedType : annotatedTypes) {

    System.out.println(annotatedType.getType() == A.class);

    for (final var a : annotatedType.getAnnotations()) {
        System.out.println(a.annotationType().getSimpleName());
    }
}

// Result
// ↓
//true
//Foo
//Bar

AnnotatedType getAnnotatedSuperclass ()

Returns an AnnotatedType object that represents the use of a type to specify the superclass of the entity represented by this Class object.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE_USE)
@interface Bar {
}
class A {
}

class B extends @Foo @Bar A {
}

final var annotatedType = B.class.getAnnotatedSuperclass();
System.out.println(annotatedType.getType() == A.class);

for (final var a : annotatedType.getAnnotations()) {
    System.out.println(a.annotationType().getSimpleName());
}

// Result
// ↓
//true
//Foo
//Bar

<A extends Annotation> A getAnnotation (Class<A> annotationClass)

Returns this element's annotation for the specified type if such an annotation is present, else null.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Bar {
}

@Foo
class A {
}

@Bar
class B extends A {
}
final var cls = B.class;

final var ret1 = cls.getAnnotation(Foo.class);
System.out.println(ret1.annotationType().getSimpleName()); // Foo

final var ret2 = cls.getAnnotation(Bar.class);
System.out.println(ret2.annotationType().getSimpleName()); // Bar
final var cls = B.class;

final var ret1 = cls.getDeclaredAnnotation(Foo.class);
System.out.println(ret1); // null

final var ret2 = cls.getDeclaredAnnotation(Bar.class);
System.out.println(ret2.annotationType().getSimpleName()); // Bar

Annotation[] getAnnotations ()

Returns annotations that are present on this element.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Bar {
}

@Foo
class A {
}

@Bar
class B extends A {
}
final var cls = B.class;

for (final var a : cls.getAnnotations()) {
    System.out.println(a.annotationType().getSimpleName());
}

// Result
// ↓
//Foo
//Bar
final var cls = B.class;

for (final var a : cls.getDeclaredAnnotations()) {
    System.out.println(a.annotationType().getSimpleName());
}

// Result
// ↓
//Bar

<A extends Annotation> A[] getAnnotationsByType (Class<A> annotationClass)

Returns annotations that are associated with this element.

@Repeatable(Bar.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Foo {
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface Bar {
    Foo[] value();
}

@Foo("a1")
@Foo("a2")
class A {
}

class B extends A {
}
System.out.println("-- A.class --");
for (final var a : A.class.getAnnotationsByType(Foo.class)) {
    System.out.println(a.annotationType().getSimpleName() + " : " + a.value());
}

System.out.println("-- B.class --");
for (final var a : B.class.getAnnotationsByType(Foo.class)) {
    System.out.println(a.annotationType().getSimpleName() + " : " + a.value());
}

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

// Result
// ↓
//-- A.class --
//Foo : a1
//Foo : a2
//-- B.class --
//Foo : a1
//Foo : a2
//-- end --
System.out.println("-- A.class --");
for (final var a : A.class.getDeclaredAnnotationsByType(Foo.class)) {
    System.out.println(a.annotationType().getSimpleName() + " : " + a.value());
}

System.out.println("-- B.class --");
for (final var a : B.class.getDeclaredAnnotationsByType(Foo.class)) {
    System.out.println(a.annotationType().getSimpleName() + " : " + a.value());
}

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

// Result
// ↓
//-- A.class --
//Foo : a1
//Foo : a2
//-- B.class --
//-- end --

String getCanonicalName ()

Returns the canonical name of the underlying class as defined by The Java Language Specification.

final var cls = String.class;

System.out.println(cls.getName()); // java.lang.String
System.out.println(cls.getTypeName()); // java.lang.String
System.out.println(cls.getCanonicalName()); // java.lang.String
System.out.println(cls.getSimpleName());  // String
final var cls = int[].class;

System.out.println(cls.getName()); // [I
System.out.println(cls.getTypeName()); // int[]
System.out.println(cls.getCanonicalName()); // int[]
System.out.println(cls.getSimpleName());  // int[]
System.out.println(getClass().getName()); // com.example.lang.system.ClassTest

final var runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Run!");
    }
};

final var cls = runnable.getClass();

System.out.println(cls.getName()); // com.example.lang.system.ClassTest$1
System.out.println(cls.getTypeName()); // com.example.lang.system.ClassTest$1
System.out.println(cls.getCanonicalName()); // null
System.out.println(cls.getSimpleName().isEmpty()); // true

Class<?>[] getClasses ()

Returns an array containing Class objects representing all the public classes and interfaces that are members of the class represented by this Class object.

public class A {
    public class Foo {
    }
}

public class B extends A {
    public class Bar {
    }

    private class Baz {
    }
}
final var cls = B.class;

for (final var c : cls.getClasses()) {
    System.out.println(c.getSimpleName());
}

// Result
// ↓
//Bar
//Foo
final var cls = B.class;

for (final var c : cls.getDeclaredClasses()) {
    System.out.println(c.getSimpleName());
}

// Result
// ↓
//Baz
//Bar

ClassLoader getClassLoader ()

Returns the class loader for the class.

final var cls = getClass();
final var loader = cls.getClassLoader();

System.out.println(loader.getName()); // app
final var loader = Object.class.getClassLoader();
System.out.println(loader); // null

Class<?> getComponentType ()

Returns the Class representing the component type of an array.

final var cls = int[].class;

System.out.println(cls.isArray()); // true
System.out.println(cls.getSimpleName()); // int[]
System.out.println(cls.getComponentType().getSimpleName()); // int
final var cls = String.class;

System.out.println(cls.isArray()); // false
System.out.println(cls.getSimpleName()); // String
System.out.println(cls.getComponentType()); // null

Constructor<T> getConstructor (Class<?>... parameterTypes)

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object.

public class Foo {
    public Foo(String s) {
    }

    public Foo(int i, double d) {
    }

    private Foo(char c) {
    }
}
final var cls = Foo.class;

final var ret1 = cls.getConstructor(String.class);
System.out.println(ret1); // public Foo(java.lang.String)

final var ret2 = cls.getConstructor(int.class, double.class);
System.out.println(ret2); // public Foo(int,double)

try {
    final var ret3 = cls.getConstructor(char.class);
} catch (NoSuchMethodException e) {
    System.out.println("NoSuchMethodException!");
}

// Result
// ↓
//NoSuchMethodException!
final var cls = Foo.class;

final var ret1 = cls.getDeclaredConstructor(String.class);
System.out.println(ret1); // public Foo(java.lang.String)

final var ret2 = cls.getDeclaredConstructor(int.class, double.class);
System.out.println(ret2); // public Foo(int,double)

final var ret3 = cls.getDeclaredConstructor(char.class);
System.out.println(ret3); // private Foo(char)

Constructor<?>[] getConstructors ()

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

public class Foo {
    public Foo(String s) {
    }

    public Foo(int i, double d) {
    }

    private Foo(char c) {
    }
}
final var cls = Foo.class;

for (final var constructor : cls.getConstructors()) {
    System.out.println(constructor);
}

// Result
// ↓
//public Foo(java.lang.String)
//public Foo(int,double)
final var cls = Foo.class;

for (final var constructor : cls.getDeclaredConstructors()) {
    System.out.println(constructor);
}

// Result
// ↓
//public Foo(java.lang.String)
//public Foo(int,double)
//private Foo(char)

<A extends Annotation> A getDeclaredAnnotation (Class<A> annotationClass)

Returns this element's annotation for the specified type if such an annotation is directly present, else null.

Please see getAnnotation(Class<A> annotationClass).

Annotation[] getDeclaredAnnotations ()

Returns annotations that are directly present on this element.

Please see getAnnotations().

<A extends Annotation> A[] getDeclaredAnnotationsByType (Class<A> annotationClass)

Returns this element's annotation(s) for the specified type if such annotations are either directly present or indirectly present.

Please see getAnnotationsByType(Class<A> annotationClass).

Class<?>[] getDeclaredClasses ()

Returns an array of Class objects reflecting all the classes and interfaces declared as members of the class represented by this Class object.

Please see getClasses().

Constructor<T> getDeclaredConstructor (Class<?>... parameterTypes)

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Please see getConstructor(Class<?>... parameterTypes).

Constructor<?>[] getDeclaredConstructors ()

Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object.

Please see getConstructors().

Field getDeclaredField (String name)

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

public class A {
    public String a1;
}

public class B extends A {
    public int b1;
    private char b2;
}
final var cls = B.class;

final var ret1 = cls.getField("a1");
System.out.println("a1 : " + ret1);

final var ret2 = cls.getField("b1");
System.out.println("b1 : " + ret2);

try {
    final var ret3 = cls.getField("b2");
} catch (NoSuchFieldException e) {
    System.out.println("b2 : NoSuchFieldException!");
}

// Result
// ↓
//a1 : public java.lang.String A.a1
//b1 : public int B.b1
//b2 : NoSuchFieldException!
final var cls = B.class;

try {
    final var ret1 = cls.getDeclaredField("a1");
} catch (NoSuchFieldException e) {
    System.out.println("a1 : NoSuchFieldException!");
}

final var ret2 = cls.getDeclaredField("b1");
System.out.println("b1 : " + ret2);

final var ret3 = cls.getDeclaredField("b2");
System.out.println("b2 : " + ret3);

// Result
// ↓
//a1 : NoSuchFieldException!
//b1 : public int B.b1
//b2 : private char B.b2

Field[] getDeclaredFields ()

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

public class A {
    public String a1;
}

public class B extends A {
    public int b1;
    private char b2;
}
final var cls = B.class;

for (final var method : cls.getFields()) {
    System.out.println(method);
}

// Result
// ↓
//public int B.b1
//public java.lang.String A.a1
final var cls = B.class;

for (final var method : cls.getDeclaredFields()) {
    System.out.println(method);
}

// Result
// ↓
//public int B.b1
//private char B.b2

Method getDeclaredMethod (String name, Class<?>... parameterTypes)

Returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

public class A {
    public void a1(String s) {
    }
}

public class B extends A {
    public void b1(int i, double d) {
    }

    private void b2() {
    }
}
final var cls = B.class;

final var ret1 = cls.getMethod("a1", String.class);
System.out.println("a1 : " + ret1);

final var ret2 = cls.getMethod("b1", int.class, double.class);
System.out.println("b1 : " + ret2);

try {
    final var ret3 = cls.getMethod("b2");
} catch (NoSuchMethodException e) {
    System.out.println("b2 : NoSuchMethodException!");
}

// Result
// ↓
//a1 : public void A.a1(java.lang.String)
//b1 : public void B.b1(int,double)
//b2 : NoSuchMethodException!
final var cls = B.class;

try {
    final var ret1 = cls.getDeclaredMethod("a1", String.class);
} catch (NoSuchMethodException e) {
    System.out.println("a1 : NoSuchMethodException!");
}

final var ret2 = cls.getDeclaredMethod("b1", int.class, double.class);
System.out.println("b1 : " + ret2);

final var ret3 = cls.getDeclaredMethod("b2");
System.out.println("b2 : " + ret3);

// Result
// ↓
//a1 : NoSuchMethodException!
//b1 : public void B.b1(int,double)
//b2 : private void B.b2()

Method[] getDeclaredMethods ()

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

public class A {
    public void a1(String s) {
    }
}

public class B extends A {
    public void b1(int i, double d) {
    }

    private void b2() {
    }
}
final var cls = B.class;

for (final var method : cls.getMethods()) {
    System.out.println(method);
}

// Result
// ↓
//public B.b1(int,double)
//public A.a1(java.lang.String)
//public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
//public final void java.lang.Object.wait() throws java.lang.InterruptedException
//public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
//public boolean java.lang.Object.equals(java.lang.Object)
//public java.lang.String java.lang.Object.toString()
//public native int java.lang.Object.hashCode()
//public final native java.lang.Class java.lang.Object.getClass()
//public final native void java.lang.Object.notify()
//public final native void java.lang.Object.notifyAll()
final var cls = B.class;

for (final var method : cls.getDeclaredMethods()) {
    System.out.println(method);
}

// Result
// ↓
//private void B.b2()
//public void B.b1(int,double)

Class<?> getDeclaringClass ()

If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared.

class Foo {
    class Bar {
    }
}

System.out.println(Foo.Bar.class.getDeclaringClass()); // Foo
System.out.println(Foo.class.getDeclaringClass()); // null

System.out.println(String.class.getDeclaringClass()); // null
System.out.println(int.class.getDeclaringClass()); // null

Class<?> getEnclosingClass ()

Returns the immediately enclosing class of the underlying class.

class OuterA {
    class InnerB {
    }
}

final var cls = OuterA.InnerB.class;

System.out.println(cls.getSimpleName()); // InnerB
System.out.println(cls.getEnclosingClass().getSimpleName()); // OuterA

Constructor<?> getEnclosingConstructor ()

If this Class object represents a local or anonymous class within a constructor, returns a Constructor object representing the immediately enclosing constructor of the underlying class.

class Foo {
    Foo() {
        class Bar {
        }

        final var cls = Bar.class;
        System.out.println("cls : " + cls.getSimpleName());

        final var ret = cls.getEnclosingConstructor();
        System.out.println("ret : " + ret);
    }
}
new Foo();

// Result
// ↓
//cls : Bar
//ret : Foo()

Method getEnclosingMethod ()

If this Class object represents a local or anonymous class within a method, returns a Method object representing the immediately enclosing method of the underlying class.

class Foo {
    void aaa() {
        class Bar {
        }

        final var cls = Bar.class;
        System.out.println("cls : " + cls.getSimpleName());

        final var ret = cls.getEnclosingMethod();
        System.out.println("ret : " + ret);

    }
}

new Foo().aaa();

// Result
// ↓
//cls : Bar
//ret : void Foo.aaa()

T[] getEnumConstants ()

Returns the elements of this enum class or null if this Class object does not represent an enum class.

enum Foo {
    C1,
    C2,
    C3,
}

final var cls = Foo.class;
System.out.println(cls.isEnum());

System.out.println("-- for --");
for (final var constant : cls.getEnumConstants()) {
    System.out.println(constant);
}

// Result
// ↓
//true
//-- for --
//C1
//C2
//C3

Field getField (String name)

Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.

Please see getDeclaredField(String name).

Field[] getFields ()

Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.

Please see getDeclaredFields().

Type[] getGenericInterfaces ()

Returns the Types representing the interfaces directly implemented by the class or interface represented by this Class object.

interface A1 {
}

interface A2<T> {
}

class B implements A1, A2<String> {
}

final var cls = B.class;

System.out.println("-- getInterfaces --");
for (final var i : cls.getInterfaces()) {
    System.out.println(i);
}

System.out.println("-- getGenericInterfaces --");
for (final var i : cls.getGenericInterfaces()) {
    System.out.println(i);
}

// Result
// ↓
//-- getInterfaces --
//interface A1
//interface A2
//-- getGenericInterfaces --
//interface A1
//A2<java.lang.String>

Type getGenericSuperclass ()

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class object.

class A<T> {
}

class B extends A<String> {
}

final var cls = B.class;

System.out.println(cls.getSuperclass()); // class A
System.out.println(cls.getGenericSuperclass()); // A<java.lang.String>

Class<?>[] getInterfaces ()

Returns the interfaces directly implemented by the class or interface represented by this Class object.

Please see getGenericInterfaces().

Method getMethod (String name, Class<?>... parameterTypes)

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Please see getDeclaredMethod(String name, Class<?>... parameterTypes).

Method[] getMethods ()

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Please see getDeclaredMethods().

int getModifiers ()

Returns the Java language modifiers for this class or interface, encoded in an integer.

public class A {
}

protected class B {
}

private class C {
}

class D {
}
final var a = A.class.getModifiers();
System.out.println(a); // 1
System.out.println(Modifier.isPublic(a)); // true

final var b = B.class.getModifiers();
System.out.println(b); // 4
System.out.println(Modifier.isProtected(b)); // true

final var c = C.class.getModifiers();
System.out.println(c); // 2
System.out.println(Modifier.isPrivate(c)); // true

final var d = D.class.getModifiers();
System.out.println(d); // 0

Module getModule ()

Returns the module that this class or interface is a member of.

final var cls = Object.class;

System.out.println(cls.getModule()); // module java.base
System.out.println(cls.getPackage()); // package java.lang
final var cls = Node.class;

System.out.println(cls.getModule()); // module java.xml
System.out.println(cls.getPackage()); // package org.w3c.dom

String getName ()

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object.

Please see getCanonicalName().

Class<?> getNestHost ()

Returns the nest host of the nest to which the class or interface represented by this Class object belongs.

public class NestTest {

    class Foo {
    }

    class Bar {
    }

    public static void main(String[] args) {

        System.out.println("host : " + Foo.class.getNestHost());

        System.out.println("-- member --");
        for (final var member : Bar.class.getNestMembers()) {
            System.out.println(member);
        }

        // Result
        // ↓
        //host : class NestTest
        //-- member --
        //class NestTest
        //class NestTest$Bar
        //class NestTest$Foo
    }
}

Class<?>[] getNestMembers ()

Returns an array containing Class objects representing all the classes and interfaces that are members of the nest to which the class or interface represented by this Class object belongs.

Please see getNestHost().

Package getPackage ()

Gets the package of this class.

final var cls = Object.class;

System.out.println(cls.getPackage()); // package java.lang
System.out.println(cls.getPackageName()); // java.lang
final var cls = Node.class;

System.out.println(cls.getPackage()); // package org.w3c.dom
System.out.println(cls.getPackageName()); // org.w3c.dom

String getPackageName ()

Returns the fully qualified package name.

Please see getPackage().

Class<?>[] getPermittedSubclasses ()

Returns an array containing Class objects representing the direct subinterfaces or subclasses permitted to extend or implement this class or interface if it is sealed.

sealed class A permits B1, B2 {
}

final class B1 extends A {
}

final class B2 extends A {
}
final var cls = A.class;

for (final var c : cls.getPermittedSubclasses()) {
    System.out.println(c);
}

// Result
// ↓
//class B1
//class B2

ProtectionDomain getProtectionDomain ()

Returns the ProtectionDomain of this class.

final var cls = String.class;

System.out.println(cls.getProtectionDomain());

// Result
// ↓
//ProtectionDomain  null
// null
// <no principals>
// java.security.Permissions@4f0f2942 (
// ("java.security.AllPermission" "<all permissions>" "<all actions>")
//)

RecordComponent[] getRecordComponents ()

Returns an array of RecordComponent objects representing all the record components of this record class, or null if this class is not a record class.

record Foo(int num, String str) {
}

final var cls = Foo.class;

for (final var component : cls.getRecordComponents()) {
    System.out.println(component);
}

// Result
// ↓
//int num
//java.lang.String str

URL getResource (String name)

Finds a resource with a given name.

// ResourceTest.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ResourceTest {

    public static void main(String[] args) {

        final var cls = ResourceTest.class;

        final var url = cls.getResource("/res/aaa.txt");
        if (url == null) {
            System.out.println("Not found!");
            return;
        }

        System.out.println("url : " + url);

        try (final var reader = new BufferedReader(
                new InputStreamReader(url.openStream()))) {

            reader.lines().forEach(line -> System.out.println("line : " + line));

        } catch (IOException e) {
            System.out.println(e);
        }

        // --- PowerShell ---
        //PS R:\java-work> tree /F
        //...
        //R:.
        //│  ResourceTest.java
        //│
        //└─res
        //        aaa.txt
        //
        //PS R:\java-work> cat .\res\aaa.txt
        //abcd
        //
        //PS R:\java-work> java .\ResourceTest.java
        //url : file:/R:/java-work/res/aaa.txt
        //line : abcd
    }
}

InputStream getResourceAsStream (String name)

Finds a resource with a given name.

// ResourceTest2.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ResourceTest2 {

    public static void main(String[] args) {

        final var cls = ResourceTest2.class;

        final var is = cls.getResourceAsStream("/res/aaa.txt");
        if (is == null) {
            System.out.println("Not found!");
            return;
        }

        try (final var reader = new BufferedReader(new InputStreamReader(is))) {

            reader.lines().forEach(line -> System.out.println("line : " + line));

        } catch (IOException e) {
            System.out.println(e);
        }

        // --- PowerShell ---
        //PS R:\java-work> tree /F
        //...
        //R:.
        //│  ResourceTest2.java
        //│
        //└─res
        //        aaa.txt
        //
        //PS R:\java-work> cat .\res\aaa.txt
        //abcd
        //
        //PS R:\java-work> java .\ResourceTest2.java
        //line : abcd
    }
}

Object[] getSigners ()

Gets the signers of this class.

final var cls = Object.class;

final var ret = cls.getSigners();
System.out.println(Arrays.toString(ret)); // null

String getSimpleName ()

Returns the simple name of the underlying class as given in the source code.

Please see getCanonicalName().

Class<? super T> getSuperclass ()

Returns the Class representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class.

Please see getGenericSuperclass().

String getTypeName ()

Return an informative string for the name of this class or interface.

System.out.println(Object.class.getTypeName()); // java.lang.Object
System.out.println(int.class.getTypeName()); // int
System.out.println(String[].class.getTypeName()); // java.lang.String[]

TypeVariable<Class<T>>[] getTypeParameters ()

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

class Foo<T, R, U> {
}

final var cls = Foo.class;

System.out.println("-- for --");
for (final var param : cls.getTypeParameters()) {
    System.out.println(param);
}

// Result
// ↓
//-- for --
//T
//R
//U

boolean isAnnotation ()

Returns true if this Class object represents an annotation interface.

class Foo {
}

@interface Bar {
}
System.out.println(Foo.class.isAnnotation()); // false
System.out.println(Bar.class.isAnnotation()); // true

System.out.println(String.class.isAnnotation()); // false
System.out.println(Override.class.isAnnotation()); // true

boolean isAnnotationPresent (Class<? extends Annotation> annotationClass)

Returns true if an annotation for the specified type is present on this element, else false.

@Retention(RetentionPolicy.RUNTIME)
@interface Foo {
}

@Retention(RetentionPolicy.RUNTIME)
@interface Bar {
}
@Foo
class A {
}

final var cls = A.class;

System.out.println(cls.isAnnotationPresent(Foo.class)); // true
System.out.println(cls.isAnnotationPresent(Bar.class)); // false

boolean isAnonymousClass ()

Returns true if and only if the underlying class is an anonymous class.

final var r1 = new Runnable() {
    @Override
    public void run() {
        System.out.println("Run!");
    }
};

final Runnable r2 = () -> System.out.println("Run!");

System.out.println(r1.getClass().isAnonymousClass()); // true
System.out.println(r2.getClass().isAnonymousClass()); // false

System.out.println(String.class.isAnonymousClass()); // false
System.out.println(int.class.isAnonymousClass()); // false

boolean isArray ()

Determines if this Class object represents an array class.

System.out.println(String[].class.isArray()); // true
System.out.println(int[].class.isArray()); // true

System.out.println(Object.class.isArray()); // false
System.out.println(Runnable.class.isArray()); // false

boolean isAssignableFrom (Class<?> cls)

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.

class A {
}

class B extends A {
}

System.out.println(A.class.isAssignableFrom(A.class)); // true

System.out.println(A.class.isAssignableFrom(B.class)); // true
System.out.println(B.class.isAssignableFrom(A.class)); // false
interface A {
}

class B implements A {
}

System.out.println(A.class.isAssignableFrom(B.class)); // true
System.out.println(B.class.isAssignableFrom(A.class)); // false

boolean isEnum ()

Returns true if and only if this class was declared as an enum in the source code.

enum Foo {
    A1,
    A2
}

System.out.println(Foo.class.isEnum()); // true
System.out.println(String.class.isEnum()); // false
System.out.println(int.class.isEnum()); // false

boolean isHidden ()

Returns true if and only if the underlying class is a hidden class.

// --- PowerShell ---
//PS R:\java-work> cat .\HiddenTest.java
//public class HiddenTest {
//}
//
//PS R:\java-work> javac .\HiddenTest.java

final var file = Path.of("R:", "java-work", "HiddenTest.class");
final var bytes = Files.readAllBytes(file);

final var lookup = MethodHandles.lookup();

final var cls = lookup.defineHiddenClass(bytes, false).lookupClass();
System.out.println(cls.isHidden()); // true
System.out.println(String.class.isHidden()); // false
System.out.println(int.class.isHidden()); // false

boolean isInstance (Object obj)

Determines if the specified Object is assignment-compatible with the object represented by this Class.

class Foo {
}

class Bar extends Foo {
}

final var foo = new Foo();
final var bar = new Bar();

System.out.println(Foo.class.isInstance(foo)); // true
System.out.println(Foo.class.isInstance(bar)); // true

System.out.println(Bar.class.isInstance(foo)); // false
System.out.println(Bar.class.isInstance(bar)); // true

boolean isInterface ()

Determines if this Class object represents an interface type.

interface Foo {
}

class Bar {
}

System.out.println(Foo.class.isInterface()); // true
System.out.println(Bar.class.isInterface()); // false

System.out.println(String.class.isInterface()); // false
System.out.println(int.class.isInterface()); // false

boolean isLocalClass ()

Returns true if and only if the underlying class is a local class.

class Foo {

    void aaa() {

        System.out.println("Foo : " + Foo.class.isLocalClass());

        class Bar {
        }

        System.out.println("Bar : " + Bar.class.isLocalClass());
    }
}
new Foo().aaa();

// Result
// ↓
//Foo : false
//Bar : true

boolean isMemberClass ()

Returns true if and only if the underlying class is a member class.

public class MemberClassTest {

    public class Foo {
    }

    public interface Bar {
    }
}
System.out.println(MemberClassTest.class.isMemberClass()); // false
System.out.println(MemberClassTest.Foo.class.isMemberClass()); // true
System.out.println(MemberClassTest.Bar.class.isMemberClass()); // true

System.out.println(String.class.isMemberClass()); // false
System.out.println(int.class.isMemberClass()); // false

boolean isNestmateOf (Class<?> c)

Determines if the given Class is a nestmate of the class or interface represented by this Class object.

class A1 {
    class A2 {
        class A3 {
        }
    }
}
System.out.println(A1.class.isNestmateOf(A1.class)); // true
System.out.println(A1.class.isNestmateOf(A1.A2.class)); // true
System.out.println(A1.class.isNestmateOf(A1.A2.A3.class)); // true
System.out.println(A1.class.isNestmateOf(String.class)); // false

System.out.println(A1.A2.A3.class.isNestmateOf(A1.class)); // true
System.out.println(A1.A2.A3.class.isNestmateOf(A1.A2.class)); // true
System.out.println(A1.A2.A3.class.isNestmateOf(A1.A2.A3.class)); // true
System.out.println(A1.A2.A3.class.isNestmateOf(String.class)); // false

boolean isPrimitive ()

Determines if the specified Class object represents a primitive type.

System.out.println(int.class.isPrimitive()); // true
System.out.println(int[].class.isPrimitive()); // false

System.out.println(String.class.isPrimitive()); // false
System.out.println(Runnable.class.isPrimitive()); // false

boolean isRecord ()

Returns true if and only if this class is a record class.

record Foo() {
}

class Bar {
}

interface Baz {
}

System.out.println(Foo.class.isRecord()); // true
System.out.println(Bar.class.isRecord()); // false
System.out.println(Baz.class.isRecord()); // false

System.out.println(int.class.isRecord()); // false
System.out.println(Foo[].class.isRecord()); // false

boolean isSealed ()

Returns true if and only if this Class object represents a sealed class or interface.

sealed class A permits B {
}

final class B extends A {
}

class C {
}
System.out.println(A.class.isSealed()); // true
System.out.println(B.class.isSealed()); // false
System.out.println(C.class.isSealed()); // false

System.out.println(int.class.isSealed()); // false
System.out.println(A[].class.isSealed()); // false

boolean isSynthetic ()

Returns true if and only if this class has the synthetic modifier bit set.

System.out.println(String.class.isSynthetic()); // false
System.out.println(int.class.isSynthetic()); // false

final Runnable r = () -> System.out.println("Run!");
System.out.println(r.getClass().isSynthetic()); // true

T newInstance ()

Deprecated. This method propagates any exception thrown by the nullary constructor, including a checked exception.

Deprecated.

String toGenericString ()

Returns a string describing this Class, including information about modifiers and type parameters.

final var ret1 = String.class.toGenericString();
System.out.println(ret1); // public final class java.lang.String

final var ret2 = Runnable.class.toGenericString();
System.out.println(ret2); // public abstract interface java.lang.Runnable

final var ret3 = DayOfWeek.class.toGenericString();
System.out.println(ret3); // public final enum java.time.DayOfWeek
final var ret1 = int.class.toGenericString();
System.out.println(ret1); // int

final var ret2 = String[].class.toGenericString();
System.out.println(ret2); // java.lang.String[]

String toString ()

Converts the object to a string.

final var ret1 = String.class.toString();
System.out.println(ret1); // class java.lang.String

final var ret2 = Runnable.class.toString();
System.out.println(ret2); // interface java.lang.Runnable

final var ret3 = DayOfWeek.class.toString();
System.out.println(ret3); // class java.time.DayOfWeek
final var ret1 = int.class.toString();
System.out.println(ret1); // int

final var ret2 = String[].class.toString();
System.out.println(ret2); // class [Ljava.lang.String;

Related posts

To top of page