构造函数的反射
1 import java.lang.reflect.Constructor;
2
3 public class zzbds {
4 public static void main(String[] args) {
5
6 try{
7 Class c=Student.class;
//獲得無參構造函數 8 Constructor constructor=c.getConstructor(new Class[]{});
//生成函數對象 9 Student k=(Student)constructor.newInstance(new Object[]{}); 10 k.setAge(0); 11 System.out.println(k.getAge()); 12 13 //獲取有參構造函數 14 Constructor constructor1=c.getConstructor(new Class[]{String.class,int.class}); 15 Student k1=(Student)constructor1.newInstance(new Object[]{"zhangsan",30}); 16 System.out.println(k1.getName()); 17 } catch (Exception e) { 18 19 } 20 21 22 }} 23 class Student{ 24 String name; 25 int age; 26 public String getName() { 27 return name; 28 } 29 public void setName(String name) { 30 this.name = name; 31 } 32 public int getAge() { 33 return age; 34 } 35 public void setAge(int age) { 36 this.age = age; 37 } 38 public Student(String name, int age) { 39 super(); 40 this.name = name; 41 this.age = age; 42 } 43 public Student() { 44 System.out.println("我是無參構造方法!"); 45 } 46 }
7 Class c=Student.class;
//獲得無參構造函數 8 Constructor constructor=c.getConstructor(new Class[]{});
//生成函數對象 9 Student k=(Student)constructor.newInstance(new Object[]{}); 10 k.setAge(0); 11 System.out.println(k.getAge()); 12 13 //獲取有參構造函數 14 Constructor constructor1=c.getConstructor(new Class[]{String.class,int.class}); 15 Student k1=(Student)constructor1.newInstance(new Object[]{"zhangsan",30}); 16 System.out.println(k1.getName()); 17 } catch (Exception e) { 18 19 } 20 21 22 }} 23 class Student{ 24 String name; 25 int age; 26 public String getName() { 27 return name; 28 } 29 public void setName(String name) { 30 this.name = name; 31 } 32 public int getAge() { 33 return age; 34 } 35 public void setAge(int age) { 36 this.age = age; 37 } 38 public Student(String name, int age) { 39 super(); 40 this.name = name; 41 this.age = age; 42 } 43 public Student() { 44 System.out.println("我是無參構造方法!"); 45 } 46 }
?
轉載于:https://www.cnblogs.com/lgshiwoo/p/5549570.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
- 上一篇: YYModel Summary
- 下一篇: 垂直居中-父元素高度确定的多行文本(方法