java创建对象_java 创建对象的五种方式
通過?Class?對象的?getConstructor?可以獲取?java.lang.reflect.Constructor?對象
Constructor?對象用來描述類的構造方法,通過給?getConstructor?方法傳入不同的?Class?對象,可以獲取到對應的無參或有參數的構造方法
通過?Constructor?的?newInstance?方法我們就可以實例化對應的類了,但是被實例化的類必須具有對應的構造方法,并且參數必須都是類類型,而不是基本類型
/**
* 2017/3/12.
* Created by techlog
*/
public class Wall {
private Wall() {
System.out.println("Here is Wall()");
}
public Wall(Integer a) {
System.out.println("Here is Wall(" + a + ")");
}
public static void main(String[] argv) throws NoSuchMethodException {
try {
Class> classObj = Wall.class;
Constructor> constructor = classObj.getConstructor(Integer.class);
constructor.newInstance(5);
} catch (Exception e) {
e.printStackTrace();
}
}
}
總結
以上是生活随笔為你收集整理的java创建对象_java 创建对象的五种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows nodejs mysql
- 下一篇: java jdk 1.8 安装_下载、安