How do I annotate a class or method?

This example show you how to use the HelloAnnotation annotation on the previous example code, How do I create a simple annotation?. We add the HelloAnnotation annotation to our class and its methods.

package org.kodejava.lang.annotation;

@HelloAnnotation(value = "Good Morning", greetTo = "Universe")
public class HelloAnnotationExample {
    public static void main(String[] args) {
        HelloAnnotationExample hello = new HelloAnnotationExample();
        hello.sayHi();
        hello.sayHello();
    }

    @HelloAnnotation(value = "Hi there", greetTo = "Alice")
    private void sayHi() {
    }

    @HelloAnnotation(value = "Hello there", greetTo = "Bob")
    private void sayHello() {
    }
}

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.lang.reflect;

import java.lang.reflect.Constructor;

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

        // Get all declared constructors 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<?>[] parameterTypes = constructor.getParameterTypes();
            for (Class<?> c : parameterTypes) {
                System.out.println("Param type name = " + c.getName());
            }
            System.out.println("----------------------------------------");
        }

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

How do I get fields of a class object?

The example below using reflection to obtain the fields of a class object. We’ll get the field names and their corresponding type. There are three ways shown below which can be used to get an object fields:

  • Class.getDeclaredFields()
  • Class.getFields()
  • Class.getField(String)
package org.kodejava.lang.reflect;

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

public class GetFields {
    public Long id;
    protected String name;
    private Date birthDate;
    Double weight;

    public static void main(String[] args) {
        GetFields object = new GetFields();
        Class<? extends GetFields> clazz = object.getClass();

        // Get all object fields including public, protected, package and private
        // access fields.
        Field[] fields = clazz.getDeclaredFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("\n----------------------------------------\n");

        // Get all object accessible public fields.
        fields = clazz.getFields();
        System.out.println("Number of fields = " + fields.length);
        for (Field field : fields) {
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        }

        System.out.println("\n----------------------------------------\n");

        try {
            // Get field name id with public access modifier
            Field field = clazz.getField("id");
            System.out.println("Field name = " + field.getName());
            System.out.println("Field type = " + field.getType().getName());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

The output of the code snippet above are:

Number of fields = 4
Field name = id
Field type = java.lang.Long
Field name = name
Field type = java.lang.String
Field name = birthDate
Field type = java.util.Date
Field name = weight
Field type = java.lang.Double

----------------------------------------

Number of fields = 1
Field name = id
Field type = java.lang.Long

----------------------------------------

Field name = id
Field type = java.lang.Long

How do I invoke a method using Method class?

This example demonstrate using reflection to invoke methods of a class object. Using reflection we can call method of an object using the given string name of the method. When using this method we need to catch for the NoSuchMethodException, IllegalAccessException and InvocationTargetException.

package org.kodejava.lang.reflect;

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class InvokingMethod {
    public static void main(String[] args) {
        InvokingMethod object = new InvokingMethod();
        Class<? extends InvokingMethod> clazz = object.getClass();

        try {
            // Invoking the add(int, int) method
            Method method = clazz.getMethod("add", int.class, int.class);
            Object result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

            // Invoking the multiply(int, int) method
            method = clazz.getMethod("multiply", int.class, int.class);
            result = method.invoke(object, 10, 10);
            System.out.println("Result = " + result);

        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public int add(int numberA, int numberB) {
        return numberA + numberB;
    }

    public int multiply(int numberA, int numberB) {
        return numberA * numberB;
    }
}

How do I get the methods of a class object?

In this example we show you how to get the methods available in a class object. We show three ways to get the methods, they are:

  • Class.getDeclaredMethods()
  • Class.getMethods()
  • Class.getMethod(String, Class<?>...)
package org.kodejava.lang.reflect;

import java.lang.reflect.Method;

public class GetMethods {
    public static void main(String[] args) {
        GetMethods object = new GetMethods();
        Class<? extends GetMethods> clazz = object.getClass();

        // Get all declared methods including public, protected, private and
        // package (default) access but excluding the inherited methods.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("Method name        = " + method.getName());
            System.out.println("Method return type = " + method.getReturnType().getName());

            Class<?>[] paramTypes = method.getParameterTypes();
            for (Class<?> c : paramTypes) {
                System.out.println("Param type         = " + c.getName());
            }

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

        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

        // Get all methods including the inherited method. Using the getMethods()
        // we can only access public methods.
        methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println("Method name        = " + method.getName());
            System.out.println("Method return type = " + method.getReturnType().getName());

            Class<?>[] paramTypes = method.getParameterTypes();
            for (Class<?> c : paramTypes) {
                System.out.println("Param type         = " + c.getName());
            }

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

        try {
            // We can also get method by their name and parameter types, here we
            // are trying to get the add(int, int) method.
            Method method = clazz.getMethod("add", int.class, int.class);
            System.out.println("Method name: " + method.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public int add(int numberA, int numberB) {
        return numberA + numberB;
    }

    protected int multiply(int numberA, int numberB) {
        return numberA * numberB;
    }

    private double div(int numberA, int numberB) {
        return numberA / numberB;
    }
}

How do I get the path from where a class is loaded?

This examples shows how to get a path name or location from where our class is loaded.

package org.kodejava.lang;

public class CodeSourceLocation {
    public static void main(String[] args) {
        CodeSourceLocation csl = new CodeSourceLocation();
        csl.getCodeSourceLocation();
    }

    private void getCodeSourceLocation() {
        // The location from where the class is loaded.
        System.out.println("Code source location: " +
            getClass().getProtectionDomain().getCodeSource().getLocation());
    }
}

The code snippet print the following output:

Code source location: file:/F:/Wayan/Kodejava/kodejava-example/kodejava-lang/target/classes/

How do I get the name of a class?

package org.kodejava.lang;

import java.util.Calendar;
import java.math.BigDecimal;

public class ClassName {
    public static void main(String[] args) {
        // Get the name of the classes below.
        Class<?> clazz = String.class;
        System.out.println("Class Name: " + clazz.getName());

        clazz = Calendar.class;
        System.out.println("Class Name: " + clazz.getName());

        clazz = BigDecimal.class;
        System.out.println("Class Name: " + clazz.getName());
    }
}

The result of the code snippet above are:

Class Name: java.lang.String
Class Name: java.util.Calendar
Class Name: java.math.BigDecimal

How do I know if a class object is an interface or a class?

package org.kodejava.lang;

public class CheckForInterface {
    public static void main(String[] args) {
        // Checking whether Cloneable is an interface or class
        Class<?> clazz = Cloneable.class;
        boolean isInterface = clazz.isInterface();
        System.out.println(clazz.getName() + " is an interface = " + isInterface);

        // Checking whether String is an interface or class
        clazz = String.class;
        isInterface = clazz.isInterface();
        System.out.println(clazz.getName() + " is an interface = " + isInterface);
    }
}
java.lang.Cloneable is an interface = true
java.lang.String is an interface = false

How do I get package name of a class?

To get the package name of a class we can use the getClass().getPackage() method of the inspected object.

package org.kodejava.lang;

import java.util.Date;

public class GetPackageName {
    public static void main(String[] args) {
        // Create an instance of Date class, and then obtain the class package
        // name.
        Date date = new Date();
        Package pack = date.getClass().getPackage();
        String packageName = pack.getName();
        System.out.println("Package Name = " + packageName);

        // Create an instance of our class and again get its package name
        GetPackageName object = new GetPackageName();
        packageName = object.getClass().getPackage().getName();
        System.out.println("Package Name = " + packageName);
    }
}

Our code printed the following output:

Package Name = java.util
Package Name = org.kodejava.lang

How do I get super class of an object?

To get the super class of an object we can call the object’s getClass() method. After getting the class type of the object we call the getSuperclass() method to get the superclass. Let’s see the code snippet below.

package org.kodejava.lang;

public class ObtainingSuperClass {
    public static void main(String[] args) {
        // Create an instance of String class
        Object object1 = new String("Hello");

        // Get String class super class
        Class<?> clazz1 = object1.getClass().getSuperclass();
        System.out.println("Super Class = " + clazz1);

        // Create an instance of StringIndexOutOfBoundsException class
        Object object2 = new StringIndexOutOfBoundsException("Error message");

        // Get StringIndexOutOfBoundsException class super class
        Class<?> clazz2 = object2.getClass().getSuperclass();
        System.out.println("Super Class = " + clazz2);
    }
}

The program above prints the following string:

Super Class = class java.lang.Object
Super Class = class java.lang.IndexOutOfBoundsException