如何通过反射来构建对象

如何通过反射创建对象

```java
/**
 * 如何通过反射来构建对象
 */
public class Solution {
    private String str;
    private int num;

    public Solution(){

    }

    public Solution(String str, int num) {
        this.str = str;
        this.num = num;
    }

    public Solution(String str) {
        this.str = str;
    }

    public static void main(String[] args) throws Exception {
        Solution solution = Solution.class.newInstance();
        Solution solution1 = solution.getClass().newInstance();
        Class<?> solution2 = Class.forName("com.Solution");
        Solution solution3 = (Solution) solution2.newInstance();
        System.out.println(solution instanceof Solution);
        System.out.println(solution1 instanceof Solution);
        System.out.println(solution3 instanceof Solution);
        // 通过参数类型,参数个数去确定具体的构造方法
        Class[] classes = new Class[] {String.class,int.class};
        Solution hello = Solution.class.getConstructor(classes).newInstance("hello", 10);
        System.out.println(hello.str);
        // 这个方法会返回制定参数类型的所有构造器,包括public的和非public的,当然也包括private的。
        Solution hello3 = hello.getClass().getDeclaredConstructor(String.class).newInstance("hello3");
        System.out.println(hello3.str);
        // 通过无参构造方法 去创建对象  这个方法返回的是上面那个方法返回结果的子集,只返回制定参数类型访问权限是public的构造器。
        Solution solution4  = (Solution) Class.forName("com.Solution").getConstructor().newInstance();
        System.out.println(solution4 instanceof Solution);


    }
}
```

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值