class getConstructor newinstance

本文介绍了如何使用Java反射API中的getConstructor方法来获取指定构造方法并实例化对象,包括带参数构造方法及默认构造方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

  1. public static void main(String[] args) throws Exception{  
  2.         /**获取String对象指定的构造方法(通过方法的参数类型,传递 参数的 Class对象)*/  
  3.         Constructor constructor = String.class.getConstructor(StringBuffer.class);//得到String对象的一个 参数是StringBuffer的构造方法  
  4.         String str = (String) constructor.newInstance(new StringBuffer("abc"));//生成对象String,当然要传递一个StringBuffer参数  
  5.         System.out.println(str);//打印值  
  6.         /**总结:这种方法是要传递参数类型和参数的值,getConstructor(...)方法的参数是一个可变参数,因为构造方法可能有多个参数*/  
  7.           
  8.         /**获取String默认的构造方法生成String对象*/  
  9.         String str1 = String.class.newInstance();  

 

转载于:https://www.cnblogs.com/ydxblog/p/8079358.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值