插入段代碼,下次回憶吧。
先新建一個Person類,代碼如下:
public class Person { PRivate String name ; private int age; public Person(){ } public Person(String name,int age){ this.name = name ; this.age = age; } Person(String name){ this.name = name; } private Person(int age){ this.age = age; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public String toString(){ return "姓名"+this.getName()+",年齡"+this.getAge(); }}
里面包含了各種構造方法和方法,下面構造一個ConstructorDemon類(注意兩個類必須在同一個包下),進行演示:
public class ConstructorDemon { public static void main(String[] args) { try { Class<?> c = Class.forName("Person"); //獲得所有公有的構造方法 System.out.println("所有共育肚餓構造方法"); Constructor[] constructor = c.getConstructors(); for(int i = 0;i<constructor.length;i++){ System.out.println(constructor[i].toGenericString()); } //獲得指定參數類型公有的參數方法 System.out.println("獲得指定類型的公有的構造方法"); try { Constructor constru = c.getConstructor(new Class[]{String.class,int.class}); System.out.println(constru.toGenericString()); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("指定類型的構造方法不存在!"); } //獲得指定的參數類型的公有方法,不限制訪問級別 System.out.println("獲得指定類型的公有的構造方法,不限制訪問級別"); try{ Constructor constru = c.getDeclaredConstructor(new Class[]{int.class}); System.out.println(constru.toGenericString());//這里獲得了一個私有的構造方法 }catch(Exception e){ e.printStackTrace(); } //獲得所有的構造方法 System.out.println("獲得所有的構造方法"); constructor = c.getDeclaredConstructors(); for(int i = 0;i<constructor.length;i++){ System.out.println(constructor[i].toGenericString()); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
點擊運行之后,運行結果如下:
所有共育肚餓構造方法public Person(java.lang.String,int)public Person()獲得指定類型的公有的構造方法public Person(java.lang.String,int)獲得指定類型的公有的構造方法,不限制訪問級別private Person(int)獲得所有的構造方法private Person(int)Person(java.lang.String)public Person(java.lang.String,int)public Person()
新聞熱點
疑難解答