java反射示例

package com.xy6;

import java.lang.reflect.Constructor;

class PersonInfo{

    public PersonInfo() {

    }
    public PersonInfo(String name){
        this.name=name;
    }
    public PersonInfo(int age){
        this.age=age;
    }
    public PersonInfo(String name, int age) {
        this.age=age;
        this.name=name;
    }
    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;
	}
    @Override
    public String toString(){
        return "["+this.name+","+this.age+"]";
    }
    private String name;
    private int age;
}

class Demo{
    public static void main(String[] args) {
        Class<?> demo=null;
        try{
            demo=Class.forName("com.xy6.PersonInfo");
        }catch (Exception e) {
            e.printStackTrace();
        }
        PersonInfo per1=null;
        PersonInfo per2=null;
        PersonInfo per3=null;
        PersonInfo per4=null;
        //取得全部的构造函数
        Constructor<?> cons[]=demo.getConstructors();
        /*
         * http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Constructor.html?is-external=true
         *
         * Constructor permits widening conversions to occur when matching the actual
         * parameters to newInstance() with the underlying constructor's formal parameters,
         * but throws an IllegalArgumentException if a narrowing conversion would occur.
         */
        try{
    		per1 = (PersonInfo)cons[0].newInstance("zlj");
			per2 = (PersonInfo)cons[1].newInstance(150);
			per3 = (PersonInfo)cons[2].newInstance("zlj",150);
			per4 = (PersonInfo)cons[3].newInstance();
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println(per1);
        System.out.println(per2);
        System.out.println(per3);
        System.out.println(per4);
    }
}


输出结果:

[zlj,0]
[null,150]
[zlj,150]
[null,0]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值