Java程序设计之Constructor

  插入段代码,下次回忆吧。

  先新建一个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()

原文地址:https://www.cnblogs.com/xiangxi/p/4711750.html