Commit 1be8f416 authored by Martin Deinhofer's avatar Martin Deinhofer
Browse files

added example for reflection

parent f1d1709e
package java_exercises4_3;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionDemo {
//simply throw all exceptions in this example
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//ctors of class Integer
for(Constructor ctor : Integer.class.getConstructors()) {
for(Class type : ctor.getParameterTypes()) {
//Get ctor with 1 parameter of type int
Constructor<Integer> ctorInt=Integer.class.getConstructor(int.class);
//Create two instances of class Integer
Integer i1=ctorInt.newInstance(2);
Integer i2=ctorInt.newInstance(5);
//Get method object for method "Integer compareTo(Integer other)"
Method mCompareTo=Integer.class.getMethod("compareTo", new Class[] {Integer.class});
//Compare two Integer objects
System.out.println("Comparison of "+i1+" and "+i2+": "+mCompareTo.invoke(i1, i2));
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment