Java/Reflection/Constructor
Содержание
- 1 Class Reflection: find out the constructor information
- 2 Constructor Reflection
- 3 Create object using Constructor object
- 4 Creating an Object Using a Constructor Object
- 5 Get all construtors from a class
- 6 Get constructors of a class object
- 7 Getting a Constructor of a Class Object: By obtaining a list of all Constructors object
- 8 Getting a Constructor of a Class Object: By obtaining a particular Constructor object.
- 9 Has Declared Constructor
- 10 Object Reflection: invoke constructor with parameters
- 11 Passing a parameter to the constructor and calling a method dynamically
Class Reflection: find out the constructor information
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for NON-COMMERCIAL purposes and without fee is hereby granted * provided that this copyright notice appears in all copies. Please refer to * the file "copyright.html" for further important copyright and licensing * information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. */
import java.awt.Rectangle; import java.lang.reflect.Constructor; public class SampleConstructor {
public static void main(String[] args) { Rectangle r = new Rectangle(); showConstructors(r); } static void showConstructors(Object o) { Class c = o.getClass(); Constructor[] theConstructors = c.getConstructors(); for (int i = 0; i < theConstructors.length; i++) { System.out.print("( "); Class[] parameterTypes = theConstructors[i].getParameterTypes(); for (int k = 0; k < parameterTypes.length; k++) { String parameterString = parameterTypes[k].getName(); System.out.print(parameterString + " "); } System.out.println(")"); } }
}
</source>
Constructor Reflection
<source lang="java">
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionTest {
public static void main(String[] args) { String name = "java.util.Date"; try { Class cl = Class.forName(name); Class supercl = cl.getSuperclass(); System.out.print("class " + name); if (supercl != null && !supercl.equals(Object.class)) System.out.println(" extends " + supercl.getName()); System.out.print("Its constructors:"); printConstructors(cl); System.out.println(); } catch (ClassNotFoundException e) { System.out.println("Class not found."); } } public static void printConstructors(Class cl) { Constructor[] constructors = cl.getDeclaredConstructors(); for (int i = 0; i < constructors.length; i++) { Constructor c = constructors[i]; Class[] paramTypes = c.getParameterTypes(); String name = c.getName(); System.out.print(Modifier.toString(c.getModifiers())); System.out.print(" " + name + "("); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } }
}
</source>
Create object using Constructor object
<source lang="java">
import java.lang.reflect.Constructor; public class Main {
public static void main(String[] args) throws Exception { Class clazz = String.class; 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); }
}
</source>
Creating an Object Using a Constructor Object
<source lang="java">
import java.lang.reflect.Constructor; public class Main {
public static void main(String[] argv) throws Exception { Constructor con = java.awt.Point.class.getConstructor(new Class[] { int.class, int.class }); java.awt.Point obj = (java.awt.Point) con.newInstance(new Object[] { new Integer(123), new Integer(123) }); }
}
</source>
Get all construtors from a class
<source lang="java">
import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class Main{
public static void main(String args[]) throws Exception { Class c = Class.forName("MyClass"); System.out.println("Constructors:"); Constructor constructors[] = c.getDeclaredConstructors(); for (Constructor cons : constructors) System.out.println(" " + cons); }
} class MyClass {
private int count; MyClass(int c) { count = c; } MyClass() { count = 0; } void setCount(int c) { count = c; } int getCount() { return count; } void showcount() { System.out.println("count is " + count); }
}
</source>
Get constructors of a class object
<source lang="java">
import java.lang.reflect.Constructor; public class Main {
public static void main(String[] args) throws Exception { Class clazz = String.class; 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()); } } Constructor constructor = String.class.getConstructor(new Class[] { String.class }); System.out.println("Constructor = " + constructor.getName()); }
}
</source>
Getting a Constructor of a Class Object: By obtaining a list of all Constructors object
<source lang="java">
import java.lang.reflect.Constructor; public class Main {
public static void main(String[] argv) throws Exception { Constructor[] cons = String.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) { Class[] paramTypes = cons[i].getParameterTypes(); System.out.println(cons[i]); } }
}
</source>
Getting a Constructor of a Class Object: By obtaining a particular Constructor object.
<source lang="java">
import java.lang.reflect.Constructor; public class Main {
public static void main(String[] argv) throws Exception { Constructor con = java.awt.Point.class.getConstructor(new Class[] { int.class, int.class }); System.out.println(con); }
}
</source>
Has Declared Constructor
<source lang="java">
import java.lang.reflect.Constructor; public class ReflectionUtils {
public static boolean hasDeclaredConstructor(Class targetClass, Class[] partypes) { Constructor constructor = null; try { constructor = targetClass.getConstructor(partypes); }catch (Exception e) { e.printStackTrace(); } return constructor != null; }
}
</source>
Object Reflection: invoke constructor with parameters
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 1995-1998 Sun Microsystems, Inc. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software and its * documentation for NON-COMMERCIAL purposes and without fee is hereby granted * provided that this copyright notice appears in all copies. Please refer to * the file "copyright.html" for further important copyright and licensing * information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS * DERIVATIVES. */
import java.awt.Rectangle; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class SampleInstance {
public static void main(String[] args) { Rectangle rectangle; Class rectangleDefinition; Class[] intArgsClass = new Class[] { int.class, int.class }; Integer height = new Integer(12); Integer width = new Integer(34); Object[] intArgs = new Object[] { height, width }; Constructor intArgsConstructor; try { rectangleDefinition = Class.forName("java.awt.Rectangle"); intArgsConstructor = rectangleDefinition .getConstructor(intArgsClass); rectangle = (Rectangle) createObject(intArgsConstructor, intArgs); } catch (ClassNotFoundException e) { System.out.println(e); } catch (NoSuchMethodException e) { System.out.println(e); } } public static Object createObject(Constructor constructor, Object[] arguments) { System.out.println("Constructor: " + constructor.toString()); Object object = null; try { object = constructor.newInstance(arguments); System.out.println("Object: " + object.toString()); return object; } catch (InstantiationException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (IllegalArgumentException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } return object; }
}
</source>
Passing a parameter to the constructor and calling a method dynamically
<source lang="java">
public class Main {
public static void main(String args[]) throws Exception{ String name = "java.lang.String"; String methodName = "toLowerCase"; Class cl = Class.forName(name); java.lang.reflect.Constructor constructor = cl.getConstructor(new Class[] { String.class }); Object invoker = constructor.newInstance(new Object[] { "AAA" }); Class arguments[] = new Class[] {}; java.lang.reflect.Method objMethod = cl.getMethod(methodName, arguments); Object result = objMethod.invoke(invoker, (Object[]) arguments); System.out.println(result); }
}
</source>