listing28.2.java
来自「java 完全探索的随书源码」· Java 代码 · 共 79 行
JAVA
79 行
/* * Requestor */import java.lang.reflect.*;public class Requestor { // Return an array of Provider instances that // includes an instance created with each // constructor declared by the class public static Provider[] constructProvider() { Provider[] prov = null; try { // load the class and retrieve its constructors Class cl = Class.forName("Provider"); Constructor[] con = cl.getDeclaredConstructors(); // allocate the Provider array based on the // number of constructors found prov = new Provider[con.length]; for (int i=0; i<con.length; i++) { // get parameter info for the constructor Class param[] = con[i].getParameterTypes(); // create an array to hold the number of // parameters required by this constructor Object paramValues[] = new Object[param.length]; // look at each parameter type for (int x=0; x<param.length; x++) { if (!param[x].isPrimitive()) { System.out.println("param:" + param[x]); // create an object of this parameter type // using its no-argument constructor paramValues[x] = param[x].newInstance(); } } // the parameter array has been loaded, so create // an object using this Provider constructor prov[i] = (Provider)con[i].newInstance(paramValues); } } catch (InvocationTargetException e) { System.out.println("Could not get class info"); } catch (Exception e) { System.out.println("Exception during construction"); } // return the array of Providers return prov; } public static void main(String args[]) { // create a Provider instance from each constructor Provider[] prov = Requestor.constructProvider(); for (int i=0; i<prov.length; i++) { // display the Provider's one attribute to see which // constructor it was created by System.out.println("Created provider with attribute: " + prov[i].attribute); } }}/* * Provider * A simple class with one field and two constructors */class Provider{ String attribute; // Declare a no-argument constructor public Provider(){ attribute = "Not specified"; } // Declare a single-argument constructor public Provider(String s){ attribute = s; }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?