继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Java Reflection API [二]

LearningForever
关注TA
已关注
手记 6
粉丝 2
获赞 70

newInstance() method

The newInstance() method of Class class and Constructor class is used to create a new instance of the class.

The newInstance() method of Class class can invoke zero-argument constructor whereas newInstance() method of Constructor class can invoke any number of arguments. So Constructor class is preferred over Class class.

Syntax of newInstance() method of Class class

public T newInstance()throws InstantiationException,IllegalAccessException

Here T is the generic version. You can think it like Object class. You will learn about generics later.

Example of newInstance() method

Let's see the simple example to use newInstance() method.

class Simple{  
 void message(){System.out.println("Hello Java");}  
}  

class Test{  
 public static void main(String args[]){  
  try{  
  Class c=Class.forName("Simple");  
  Simple s=(Simple)c.newInstance();  
  s.message();  

  }catch(Exception e){System.out.println(e);}  

 }  
}  

source:
https://www.javatpoint.com/new-instance()-method

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP