JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Get Methods Return Type using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

In this example we shall explain with a simple example to get the methods of a class using the reflection and get the return type. You can list the public and private methods of an object using the following steps:

  • Get the Class instance of the class which you want to list the methods. In this example get the Class instance of Math class.
  • Call getMethods() method from the Class instance which returns the Method[] array which contains the public methods.
  • Call getDeclaredMethods() method from the Class instance which returns the Method[] array which contains all the methods whether it is private, public or default.
  • Then call the getReturnType() on Method object to get the return type.

Lets look at this example to list of methods and return types of java.lang.Math class:

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Method;

/**
* Get Method Return Types using Reflection
*
* @author krishna
*
*/
public class JavaBeatReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> mathClass = java.lang.Math.class;
Method[] mathMethods;
mathMethods = mathClass.getDeclaredMethods();
for (int i = 0; i < mathMethods.length; i++) {
System.out.println(mathMethods[i] + " :: return type :: "
+ mathMethods[i].getReturnType());
}
}

}
[/code]

Output

[code]
public static int java.lang.Math.abs(int) :: return type :: int
public static long java.lang.Math.abs(long) :: return type :: long
public static float java.lang.Math.abs(float) :: return type :: float
public static double java.lang.Math.abs(double) :: return type :: double
public static double java.lang.Math.sin(double) :: return type :: double
public static double java.lang.Math.cos(double) :: return type :: double
public static double java.lang.Math.tan(double) :: return type :: double
public static double java.lang.Math.atan2(double,double) :: return type :: double
public static double java.lang.Math.sqrt(double) :: return type :: double
public static double java.lang.Math.log(double) :: return type :: double
public static double java.lang.Math.log10(double) :: return type :: double
public static double java.lang.Math.pow(double,double) :: return type :: double
public static double java.lang.Math.exp(double) :: return type :: double
public static int java.lang.Math.min(int,int) :: return type :: int
public static long java.lang.Math.min(long,long) :: return type :: long
public static float java.lang.Math.min(float,float) :: return type :: float
public static double java.lang.Math.min(double,double) :: return type :: double
public static int java.lang.Math.max(int,int) :: return type :: int
public static long java.lang.Math.max(long,long) :: return type :: long
public static float java.lang.Math.max(float,float) :: return type :: float
public static double java.lang.Math.max(double,double) :: return type :: double
public static double java.lang.Math.scalb(double,int) :: return type :: double
public static float java.lang.Math.scalb(float,int) :: return type :: float
public static int java.lang.Math.getExponent(float) :: return type :: int
public static int java.lang.Math.getExponent(double) :: return type :: int
public static double java.lang.Math.signum(double) :: return type :: double
public static float java.lang.Math.signum(float) :: return type :: float
public static double java.lang.Math.asin(double) :: return type :: double
public static double java.lang.Math.acos(double) :: return type :: double
public static double java.lang.Math.atan(double) :: return type :: double
public static double java.lang.Math.toRadians(double) :: return type :: double
public static double java.lang.Math.toDegrees(double) :: return type :: double
public static double java.lang.Math.cbrt(double) :: return type :: double
public static double java.lang.Math.IEEEremainder(double,double) :: return type :: double
public static double java.lang.Math.ceil(double) :: return type :: double
public static double java.lang.Math.floor(double) :: return type :: double
public static double java.lang.Math.rint(double) :: return type :: double
public static int java.lang.Math.round(float) :: return type :: int
public static long java.lang.Math.round(double) :: return type :: long
private static synchronized void java.lang.Math.initRNG() :: return type :: void
public static double java.lang.Math.random() :: return type :: double
public static double java.lang.Math.ulp(double) :: return type :: double
public static float java.lang.Math.ulp(float) :: return type :: float
public static double java.lang.Math.sinh(double) :: return type :: double
public static double java.lang.Math.cosh(double) :: return type :: double
public static double java.lang.Math.tanh(double) :: return type :: double
public static double java.lang.Math.hypot(double,double) :: return type :: double
public static double java.lang.Math.expm1(double) :: return type :: double
public static double java.lang.Math.log1p(double) :: return type :: double
public static double java.lang.Math.copySign(double,double) :: return type :: double
public static float java.lang.Math.copySign(float,float) :: return type :: float
public static double java.lang.Math.nextAfter(double,double) :: return type :: double
public static float java.lang.Math.nextAfter(float,double) :: return type :: float
public static double java.lang.Math.nextUp(double) :: return type :: double
public static float java.lang.Math.nextUp(float) :: return type :: float
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Constructors using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to get the constructors in a class and invoke it. Note that java.lang.reflect.Constructor defines a method newInstance() which is used for creating instance for an object. Before that you have to get the list of constructors in a class. We have two methods defined in the Class class. If we use getConstructors() method, it returns only the public constructors in that class. If we use getDeclaredConstructor() method, it returns all the constructors in that class.

Lets look at the example code.

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Constructor;

/**
* Get Constructors using Reflection
*
* @author krishna
*
*/
public class JavaBeatReflectionExample {
private JavaBeatReflectionExample() {
System.out.println("Default Constructor Called");
}

public JavaBeatReflectionExample(int i) {
System.out.println("One Parameter Constructor Called");
}

public static void main(String[] args) throws Exception {
JavaBeatReflectionExample reflectionExample = new JavaBeatReflectionExample();
// Get all the constructors
Constructor cons[] = reflectionExample.getClass().getDeclaredConstructors();
cons[0].newInstance();
cons[1].newInstance(9);
}
}
[/code]

Output

[code]
Default Constructor Called
Default Constructor Called
One Parameter Constructor Called
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Super Class Name using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

With this example, we shall show you how to get the super class of an object and use it using the reflection technique. Lets look at the following example and the steps provided below to understand the program.

  • I have created Employee super class and its sub class Manager
  • Created instance of Manager and assigned to the super class reference Employee
  • Call getSuperclass() method of Class which returns the super class name.

Lets look at the example.

[code lang=”java”]
package javabeat.net.reflection;

public abstract class Employee {
public abstract String getName(String name);
}
package javabeat.net.reflection;

public class Manager extends Employee{
public String getName(String name){
return name;
}
}

package javabeat.net.reflection;

import java.lang.reflect.Method;

/**
* Get Super class name using Reflection API
*
* @author krishna
*
*/
public class JavaBeatReflectionExample {
public static void main(String[] args) throws Exception {
// Create new object of Manager
Employee employee = new Manager();

// Get super class and display it
Class<?> classVar = employee.getClass().getSuperclass();
System.out.println("Superclass = " + classVar);
Method method = employee.getClass().getMethod("getName", String.class);
System.out.println(method.invoke(employee, "Employee Name"));
}

}

[/code]

Output

[code]
Superclass = class javabeat.net.reflection.Employee
Employee Name

[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Modifiers of an Object using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

This example demonstrates how to get the modifiers used in a class using the reflection API. One can use the getModifiers() method in the Class object to know about each modifier used in that specific class. Call isAbstract(int mod), isFinal(int mod), isInterface(int mod), isNative(int mod), isPrivate(int mod), isProtected(int mod), isPublic(int mod) and isStatic(int mod) methods to know about each modifier.

Lets look at the example below to print the modifiers used in java.lang.Math class.

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Modifier;

/**
* Get Modifiers of a class using Reflection API
*
* @author krishna
*
*/
public class JavaBeatReflectionExample {
public static void main(String[] args) throws Exception {
Class<?> clazz = java.lang.Math.class;
// return the modifiers for this class or interface encoded in an integer
int mod = clazz.getModifiers();
System.out.println("Interface Modifier: " + Modifier.isInterface(mod));
System.out.println("Static Modifier: " + Modifier.isStatic(mod));
System.out.println("Abstract Modifier: " + Modifier.isAbstract(mod));
System.out.println("Final Modifier: " + Modifier.isFinal(mod));
System.out.println("Native Modifier: " + Modifier.isNative(mod));
System.out.println("Private Modifier: " + Modifier.isPrivate(mod));
System.out.println("Protected Modifier: " + Modifier.isProtected(mod));
System.out.println("Public Modifier: " + Modifier.isPublic(mod));
}

}
[/code]

Output

[code]
Interface Modifier: false
Static Modifier: false
Abstract Modifier: false
Final Modifier: true
Native Modifier: false
Private Modifier: false
Protected Modifier: false
Public Modifier: true
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Package Name using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

This example demonstrates how to get the package name using the Reflection API. With reflection we can get the details of any class or object and its methods, fields, etc. This is useful when we are doing the dynamic creation of the classes and invoking at run time.

Lets look at the example program to get the package name using reflection.

[code lang=”java”]
package javabeat.net.reflection;

/**
* Get package name using Reflection API
*
* @author krishna
*
*/
public class JavaBeatReflectionExample {
public static void main(String[] args) throws Exception {
// Create new object of this class
JavaBeatReflectionExample className = new JavaBeatReflectionExample();
// Get package name and print it
Package pack = className.getClass().getPackage();
String packageNameStr = pack.getName();
System.out.println("Package Name : " + packageNameStr);
}
}
[/code]

Output

[code]
Package Name : javabeat.net.reflection
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Methods using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

In this example we shall explain with a simple example to get the methods of a class using the reflection. You can list the public and private methods of an object using the following steps:

  • Get the Class instance of the class which you want to list the methods. In this example get the Class instance of Math class.
  • Call getMethods() method from the Class instance which returns the Method[] array which contains the public fields.
  • Call getDeclaredMethods() method from the Class instance which returns the Method[] array which contains all the methods whether it is private, public or default.

Lets look at this example to list of methods of java.lang.Math class:

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Method;
/**
* List Methods in a Class using Reflection API
* @author krishna
*
*/
public class JavaBeatReflectionExample {

public static void main(String[] args) throws Exception {

// Get the Class instance for Math
Class<?> mathClass = java.lang.Math.class;

//Declare Fields class
Method[] refMethods;

// List all the public fields in the Math class
refMethods = mathClass.getMethods();
for (int i = 0; i < refMethods.length; i++) {
System.out.println("Public Field: " + refMethods[i]);
}

System.out.println();

// List all the fields in the Math class
refMethods = mathClass.getDeclaredMethods();
for (int i = 0; i < refMethods.length; i++) {
System.out.println("Field: " + refMethods[i]);
}

}
}
[/code]

Output

[code]
Public Field: public static int java.lang.Math.abs(int)
Public Field: public static long java.lang.Math.abs(long)
Public Field: public static float java.lang.Math.abs(float)
Public Field: public static double java.lang.Math.abs(double)
Public Field: public static double java.lang.Math.sin(double)
Public Field: public static double java.lang.Math.cos(double)
Public Field: public static double java.lang.Math.tan(double)
Public Field: public static double java.lang.Math.atan2(double,double)
Public Field: public static double java.lang.Math.sqrt(double)
Public Field: public static double java.lang.Math.log(double)
Public Field: public static double java.lang.Math.log10(double)
Public Field: public static double java.lang.Math.pow(double,double)
Public Field: public static double java.lang.Math.exp(double)
Public Field: public static int java.lang.Math.min(int,int)
Public Field: public static long java.lang.Math.min(long,long)
Public Field: public static float java.lang.Math.min(float,float)
Public Field: public static double java.lang.Math.min(double,double)
Public Field: public static int java.lang.Math.max(int,int)
Public Field: public static long java.lang.Math.max(long,long)
Public Field: public static float java.lang.Math.max(float,float)
Public Field: public static double java.lang.Math.max(double,double)
Public Field: public static double java.lang.Math.scalb(double,int)
Public Field: public static float java.lang.Math.scalb(float,int)
Public Field: public static int java.lang.Math.getExponent(float)
Public Field: public static int java.lang.Math.getExponent(double)
Public Field: public static double java.lang.Math.signum(double)
Public Field: public static float java.lang.Math.signum(float)
Public Field: public static double java.lang.Math.asin(double)
Public Field: public static double java.lang.Math.acos(double)
Public Field: public static double java.lang.Math.atan(double)
Public Field: public static double java.lang.Math.toRadians(double)
Public Field: public static double java.lang.Math.toDegrees(double)
Public Field: public static double java.lang.Math.cbrt(double)
Public Field: public static double java.lang.Math.IEEEremainder(double,double)
Public Field: public static double java.lang.Math.ceil(double)
Public Field: public static double java.lang.Math.floor(double)
Public Field: public static double java.lang.Math.rint(double)
Public Field: public static int java.lang.Math.round(float)
Public Field: public static long java.lang.Math.round(double)
Public Field: public static double java.lang.Math.random()
Public Field: public static double java.lang.Math.ulp(double)
Public Field: public static float java.lang.Math.ulp(float)
Public Field: public static double java.lang.Math.sinh(double)
Public Field: public static double java.lang.Math.cosh(double)
Public Field: public static double java.lang.Math.tanh(double)
Public Field: public static double java.lang.Math.hypot(double,double)
Public Field: public static double java.lang.Math.expm1(double)
Public Field: public static double java.lang.Math.log1p(double)
Public Field: public static double java.lang.Math.copySign(double,double)
Public Field: public static float java.lang.Math.copySign(float,float)
Public Field: public static double java.lang.Math.nextAfter(double,double)
Public Field: public static float java.lang.Math.nextAfter(float,double)
Public Field: public static double java.lang.Math.nextUp(double)
Public Field: public static float java.lang.Math.nextUp(float)
Public Field: public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
Public Field: public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
Public Field: public final void java.lang.Object.wait() throws java.lang.InterruptedException
Public Field: public boolean java.lang.Object.equals(java.lang.Object)
Public Field: public java.lang.String java.lang.Object.toString()
Public Field: public native int java.lang.Object.hashCode()
Public Field: public final native java.lang.Class java.lang.Object.getClass()
Public Field: public final native void java.lang.Object.notify()
Public Field: public final native void java.lang.Object.notifyAll()

Field: public static int java.lang.Math.abs(int)
Field: public static long java.lang.Math.abs(long)
Field: public static float java.lang.Math.abs(float)
Field: public static double java.lang.Math.abs(double)
Field: public static double java.lang.Math.sin(double)
Field: public static double java.lang.Math.cos(double)
Field: public static double java.lang.Math.tan(double)
Field: public static double java.lang.Math.atan2(double,double)
Field: public static double java.lang.Math.sqrt(double)
Field: public static double java.lang.Math.log(double)
Field: public static double java.lang.Math.log10(double)
Field: public static double java.lang.Math.pow(double,double)
Field: public static double java.lang.Math.exp(double)
Field: public static int java.lang.Math.min(int,int)
Field: public static long java.lang.Math.min(long,long)
Field: public static float java.lang.Math.min(float,float)
Field: public static double java.lang.Math.min(double,double)
Field: public static int java.lang.Math.max(int,int)
Field: public static long java.lang.Math.max(long,long)
Field: public static float java.lang.Math.max(float,float)
Field: public static double java.lang.Math.max(double,double)
Field: public static double java.lang.Math.scalb(double,int)
Field: public static float java.lang.Math.scalb(float,int)
Field: public static int java.lang.Math.getExponent(float)
Field: public static int java.lang.Math.getExponent(double)
Field: public static double java.lang.Math.signum(double)
Field: public static float java.lang.Math.signum(float)
Field: public static double java.lang.Math.asin(double)
Field: public static double java.lang.Math.acos(double)
Field: public static double java.lang.Math.atan(double)
Field: public static double java.lang.Math.toRadians(double)
Field: public static double java.lang.Math.toDegrees(double)
Field: public static double java.lang.Math.cbrt(double)
Field: public static double java.lang.Math.IEEEremainder(double,double)
Field: public static double java.lang.Math.ceil(double)
Field: public static double java.lang.Math.floor(double)
Field: public static double java.lang.Math.rint(double)
Field: public static int java.lang.Math.round(float)
Field: public static long java.lang.Math.round(double)
Field: private static synchronized void java.lang.Math.initRNG()
Field: public static double java.lang.Math.random()
Field: public static double java.lang.Math.ulp(double)
Field: public static float java.lang.Math.ulp(float)
Field: public static double java.lang.Math.sinh(double)
Field: public static double java.lang.Math.cosh(double)
Field: public static double java.lang.Math.tanh(double)
Field: public static double java.lang.Math.hypot(double,double)
Field: public static double java.lang.Math.expm1(double)
Field: public static double java.lang.Math.log1p(double)
Field: public static double java.lang.Math.copySign(double,double)
Field: public static float java.lang.Math.copySign(float,float)
Field: public static double java.lang.Math.nextAfter(double,double)
Field: public static float java.lang.Math.nextAfter(float,double)
Field: public static double java.lang.Math.nextUp(double)
Field: public static float java.lang.Math.nextUp(float)
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Get Fields using Reflection

March 16, 2014 by Krishna Srinivasan Leave a Comment

In this example we shall explain with a simple example to get the fields of a class using the reflection. You can list the public and private fields of an object using the following steps:

  • Get the Class instance of the class which you want to list the fields. In this example get the Class instance of Math class.
  • Call getFields() method from the Class instance which returns the Field[] array which contains the public fields.
  • Call getDeclaredFields() method from the Class instance which returns the Field[] array which contains all the fields whether it is private, public or default.

Lets look at this example to list of fields of java.lang.Math class:

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Field;

public class JavaBeatReflectionExample {

public static void main(String[] args) throws Exception {

// Get the Class instance for Math
Class<?> mathClass = java.lang.Math.class;

//Declare Fields class
Field[] refFields;

// List all the public fields in the Math class
refFields = mathClass.getFields();
for (int i = 0; i < refFields.length; i++) {
System.out.println("Public Field: " + refFields[i]);
}

System.out.println();

// List all the fields in the Math class
refFields = mathClass.getDeclaredFields();
for (int i = 0; i < refFields.length; i++) {
System.out.println("Field: " + refFields[i]);
}

}
}
[/code]

Output

[code]
Public Field: public static final double java.lang.Math.E
Public Field: public static final double java.lang.Math.PI

Field: public static final double java.lang.Math.E
Field: public static final double java.lang.Math.PI
Field: private static java.util.Random java.lang.Math.randomNumberGenerator
Field: private static long java.lang.Math.negativeZeroFloatBits
Field: private static long java.lang.Math.negativeZeroDoubleBits
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Invoke Method using Reflection API

March 16, 2014 by Krishna Srinivasan Leave a Comment

This example highlights the way how to invoke a method using the reflection API. As we are aware that we can dynamically invoke a method in another class by using the reflection classes. Note that using reflection is more expensive in terms of performance. This programming practice is used only in the certain requirements where project needs to create dynamic classes and invoked the methods on it where we are not knowing the class name at compile time. Here this example invoke the “append” method in the StringBuffer class using the reflection API.

  • First I have created a StringBuffer class anb called append method to add the string values.
  • Use getClass() API method to get the runtime class of the StringBuffer and then getMethod(String name, Class<?>… parameterTypes) API method of Class to get the Method object that reflects the specified public member method of the class or interface represented by this Class object.
  • Once got the Method object, use the invoke (object,args) to call the method with arguments which invokes the method from the underlying original class.

Lets look at the simple example to understand the code:

[code lang=”java”]
package javabeat.net.reflection;

import java.lang.reflect.Method;

public class InvokeMethodExample {

public static void main(String[] args) throws Exception {

StringBuffer strBuffer = new StringBuffer();

strBuffer.append("JavaBeat Reflection Example");
System.out.println("Original String : " + strBuffer);

// Get the method name "append" using reflection
Method appendMethod = strBuffer.getClass().getMethod("append", String.class);

// Invoke method with arguments
appendMethod.invoke(strBuffer, " Java Programming World!!");

System.out.println("Invoked using Reflection: " + strBuffer);

}
}
[/code]

Output

[code]
Original String : JavaBeat Reflection Example
Invoked using Reflection: JavaBeat Reflection Example Java Programming World!!
[/code]

Filed Under: Java Tagged With: Core Java, Java Reflection

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved