How do I get the component type of an array?

The Class.getComponentType() method call returns the Class representing the component type of an array. If this class does not represent an array class this method returns null reference instead.

package org.kodejava.example.lang.reflect;

public class ComponentTypeDemo {
    public static void main(String[] args) {
        String[] words = {"and", "the"};
        int[][] matrix = {{1, 1}, {2, 1}};
        Double number = 10.0;

        Class clazz = words.getClass();
        Class cls = matrix.getClass();
        Class clz = number.getClass();

        //
        // Gets the type of an array component.
        //
        Class type = clazz.getComponentType();
        System.out.println("Words type: " +
                type.getCanonicalName());

        //
        // Gets the type of an array component.
        //
        Class matrixType = cls.getComponentType();
        System.out.println("Matrix type: " +
                matrixType.getCanonicalName());

        //
        // It will return null if the class doesn't represent
        // an array.
        //
        Class numberType = clz.getComponentType();
        if (numberType != null) {
            System.out.println("Number type: " +
                    numberType.getCanonicalName());
        } else {
            System.out.println(number.getClass().getName() +
                    " class is not an array");
        }
    }
}

This program print the following output:

Words type: java.lang.String
Matrix type: int[]
java.lang.Double class is not an array

How do I determine if a class object represents an array class?

For checking if a class object is representing an array class we can use the isArray() method call of the Class object. This method returns true if the checked object represents an array class and false otherwise.

package org.kodejava.example.lang.reflect;

public class IsArrayDemo {
    public static void main(String[] args) {
        int[][] matrix = {{1, 1}, {2, 1}};
        Class clazz = matrix.getClass();

        //
        // Check if the class object represents an array class
        //
        if (clazz.isArray()) {
            System.out.println(clazz.getSimpleName() +
                    " is an array class.");
        } else {
            System.out.println(clazz.getSimpleName() +
                    " is not an array class.");
        }
    }
}

How do I check if a class represent a primitive type?

Java uses class objects to represent all eight primitive types. A class object that represents a primitive type can be identified using the isPrimitive() method call. void is not a type in Java, but the isPrimitive() method returns true for void.class.

package org.kodejava.example.lang.reflect;

public class IsPrimitiveDemo {
    public static void main(String[] args) {
        IsPrimitiveDemo.get(int.class);
        IsPrimitiveDemo.get(String.class);
        IsPrimitiveDemo.get(double.class);
        IsPrimitiveDemo.get(void.class);
    }

    private static void get(Class clazz) {
        if (clazz.isPrimitive()) {
            System.out.println(clazz.getName() +
                    " is a primitive type.");
        } else {
            System.out.println(clazz.getName() +
                    " is not a primitive type.");            
        }
    }
}

Here is the result of the program:

int is a primitive type.
java.lang.String is not a primitive type.
double is a primitive type.
void is a primitive type.

How do I get information regarding class name?

package org.kodejava.example.lang.reflect;

import java.util.Date;

public class ClassNameDemo {
    public static void main(String[] args) {
        Date date = new Date();

        //
        // Gets the Class of the date instance.
        //
        Class clazz = date.getClass();

        //
        // Gets the name of the class.
        //
        String name = clazz.getName();
        System.out.println("Class name     : " + name);

        //
        // Gets the canonical name of the class.
        //
        String canonical = clazz.getCanonicalName();
        System.out.println("Canonical name : " + canonical);

        //
        // Gets the simple name of the class.
        //
        String simple = clazz.getSimpleName();
        System.out.println("Simple name    : " + simple);
    }
}

Here are the information printed out by the program:

Class name     : java.util.Date
Canonical name : java.util.Date
Simple name    : Date

How do I get direct superclass and interfaces of a class?

Java reflection also dealing with inheritance concepts. You can get the direct interfaces and direct superclass of a class by using method getInterfaces() and getSuperclass() of java.lang.Class object.

  • getInterfaces() will returns an array of Class objects that represent the direct super interfaces of the target Class object
  • getSuperclass() will returns the Class object representing the direct super class of the target Class object or null if the target represents Object class, an interface, a primitive type, or void.

 

package org.kodejava.example.lang.reflect;

import javax.swing.*;
import java.util.Date;

public class GetSuperClassDemo {
    public static void main(String[] args) {
        GetSuperClassDemo.get(String.class);
        GetSuperClassDemo.get(Date.class);
        GetSuperClassDemo.get(JButton.class);
        GetSuperClassDemo.get(Timer.class);
    }

    public static void get(Class clazz) {
        //
        // Gets array of direct interface of clazz object
        //
        Class[] interfaces = clazz.getInterfaces();

        System.out.format("Direct Interfaces of %s:%n",
                clazz.getName());
        for (Class clz : interfaces) {
            System.out.println(clz.getName());
        }

        //
        // Gets direct superclass of clazz object
        //
        Class superclz = clazz.getSuperclass();
        System.out.format("Direct Superclass of %s: is %s %n",
                clazz.getName(), superclz.getName());
        System.out.println("====================================");
    }
}

Here is the result of the code snippet:

Direct Interfaces of java.lang.String:
java.io.Serializable
java.lang.Comparable
java.lang.CharSequence
Direct Superclass of java.lang.String: is java.lang.Object 
====================================
Direct Interfaces of java.util.Date:
java.io.Serializable
java.lang.Cloneable
java.lang.Comparable
Direct Superclass of java.util.Date: is java.lang.Object 
====================================
Direct Interfaces of javax.swing.JButton:
javax.accessibility.Accessible
Direct Superclass of javax.swing.JButton: is javax.swing.AbstractButton 
====================================
Direct Interfaces of javax.swing.Timer:
java.io.Serializable
Direct Superclass of javax.swing.Timer: is java.lang.Object 
====================================

How do I check if a class represent an interface type?

You can use the isInterface() method call of the java.lang.Class to identify if a class objects represent an interface type.

package org.kodejava.example.lang.reflect;

import java.io.Serializable;

public class IsInterfaceDemo {
    public static void main(String[] args) {
        IsInterfaceDemo.get(Serializable.class);
        IsInterfaceDemo.get(Long.class);
    }

    private static void get(Class clazz) {
        if (clazz.isInterface()) {
            System.out.println(clazz.getName() +
                    " is an interface type.");
        } else {
            System.out.println(clazz.getName() +
                    " is not an interface type.");
        }
    }
}

Here is the result of the program:

java.io.Serializable is an interface type.
java.lang.Long is not an interface type.

How do I get modifiers of a class object?

package org.kodejava.example.reflect;

import java.lang.reflect.Modifier;

public class ClassModifier {
    public static void main(String[] args) {
        getClassModifier(String.class);        
        getClassModifier(TestA.class);
        getClassModifier(TestB.class);
    }

    private static void getClassModifier(Class clazz) {
        int modifier = clazz.getModifiers();

        //
        // Return true if the integer argument includes the public modifier,
        // false otherwise.
        //
        if (Modifier.isPublic(modifier)) {
            System.out.println(clazz.getName() + " class modifier is public");
        }

        //
        // Return true if the integer argument includes the protected modifier,
        // false otherwise.
        //
        if (Modifier.isProtected(modifier)) {
            System.out.println(clazz.getName() + " class modifier is protected");
        }

        //
        // Return true if the integer argument includes the private modifier,
        // false otherwise.
        //
        if (Modifier.isPrivate(modifier)) {
            System.out.println(clazz.getName() + " class modifier is private");
        }

        //
        // Return true if the integer argument includes the static modifier,
        // false otherwise.
        //
        if (Modifier.isStatic(modifier)) {
            System.out.println(clazz.getName() + " class modifier is static");
        }

        //
        // Return true if the integer argument includes the final modifier,
        // false otherwise.
        //
        if (Modifier.isFinal(modifier)) {
            System.out.println(clazz.getName() + " class modifier is final");
        }

        //
        // Return true if the integer argument includes the abstract modifier,
        // false otherwise.
        //
        if (Modifier.isAbstract(modifier)) {
            System.out.println(clazz.getName() + " class modifier is abstract");
        }
    }

    protected static final class TestA {
    }

    private abstract class TestB {
    }
}

How do I create object using Constructor object?

The example below using a constructor reflection to create a string object by calling String(String) and String(StringBuilder) constructors.

package org.kodejava.example.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class CreateObjectDemo {
    public static void main(String[] args) {
        Class clazz = String.class;

        try {
            Constructor constructor = clazz.getConstructor(new Class[] {String.class});

            String object = (String) constructor.newInstance(new Object[] {"Hello World!"});
            System.out.println("String = " + object);

            constructor = clazz.getConstructor(new Class[] {StringBuilder.class});
            object = (String) constructor.newInstance(new Object[] {new StringBuilder("Hello Universe!")});
            System.out.println("String = " + object);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

How do I get constructors of a class object?

Below is an example that showing you how to get constructors of a class object. In the code below we get the constructors by calling the Class.getDeclaredConstructors() or the Class.getConstructor(Class[]) method.

package org.kodejava.example.reflect;

import java.lang.reflect.Constructor;

public class GetConstructors {
    public static void main(String[] args) {
        Class clazz = String.class;

        //
        // Get all declared contructors and iterate the constructors to get their
        // name and parameter types.
        //
        Constructor[] constructors = clazz.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            String name = constructor.getName();
            System.out.println("Constructor name= " + name);
            
            Class[] paramterTypes = constructor.getParameterTypes();
            for (Class c : paramterTypes) {
                System.out.println("Param type name = " + c.getName());
            }
            System.out.println("----------------------------------------");
        }

        //
        // Getting a specific constructor of the java.lang.String
        //
        try {
            Constructor constructor = String.class.getConstructor(new Class[] {String.class});
            System.out.println("Constructor     = " + constructor.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

How do I get field of a class object and set or get its value?

A refection demo to get fields of a class object and set or get their value.

package org.kodejava.example.lang;

import java.util.Date;
import java.lang.reflect.Field;

public class GetSetFieldDemo {
    public static Date now;
    public Long id;
    public String name;

    public static void main(String[] args) {
        GetSetFieldDemo demo = new GetSetFieldDemo();
        Class clazz = demo.getClass();

        try {
            //
            // Get field id, set it value and read it back
            //
            Field field = clazz.getField("id");
            field.set(demo, new Long(10));
            Object value = field.get(demo);
            System.out.println("Value = " + value);

            //
            // Get static field date, set it value and read it back
            //
            field = clazz.getField("now");
            field.set(null, new Date());
            value = field.get(null);
            System.out.println("Value = " + value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}