Skip to main content

Posts

Showing posts with the label Reflection

How to Use Reflection to Get Information about a Class in Java?

-- Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. The class java.lang.Class and the package java.lang.reflect (classes Array, Constructor, Field, Method, Modifier) implement Java's reflection. The methods of java.lang.Class are used to get information about a class. The methods of the classes in java.lang.reflect provide further information about a class and allow methods to be invoked. The following example shows how to get information about java.lang.String a class: public class Program { public static void main(String[] args) { try { Class clz = Class.forName("java.lang.String"); Field[] flds = clz.getDeclaredFields(); System.out.println("\nVariables..."); for ( int k = 0; k < flds.length; k++ ) { String name = flds[k].getName(); ...

How to Use Reflection to Call Methods in Java?

-- You can invoke methods on objects dynamically. First, you must get their definition through one of the methods Class.getMethod(String,Class[]) or Class.getDeclaredMethod(String,Class[]) . The first parameter is the method??s name and the second is an array of Class objects representing the types of its parameters. The getMethod can handle inheritance but only picks up public methods. It returns the public method that matches the parameters provided, whether it is declared by the class or inherited. class Parent { public long l; public void setLong(long l) { this.l = l; } } public class Program extends Parent { public static void main(String[] args) { // Get the Class object associated with this class. Program program = new Program(); Class progClass = program.getClass(); try { // Get the method named sayHello. Method helloMethod = progClass.getMet...

How to Use Reflection to Access Fields with Enum Types of a Class in Java?

-- Java Reflection provides three enum-specific APIs: Class.isEnum() : Indicates whether this class represents an enum type Class.getEnumConstants() : Retrieves the list of enum constants defined by the enum in the order they're declared. java.lang.reflect.Field.isEnumConstant() : Indicates whether this field represents an element of an enumerated type The following example shows how to get and set fields with Java Enum Types: package com.abcd; import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out;