[英]Unable to instantiate an object using parameterized Constructor in java
This is the class I want to Instantiate: 这是我要实例化的课程:
public class GoogleSheetsAPI {
String spreadsheetId;
Sheets service;
String credentialsFile;
public void GoogleSheetsAPI() {
}
public void GoogleSheetsAPI(String spreadsheetId, String credentialsFile) throws Exception {
this.spreadsheetId = spreadsheetId;
this.credentialsFile = credentialsFile;
service = getSheetsService();
}
} }
This is how I am creating an object of class GoogleSheetsAPI
这就是我创建类
GoogleSheetsAPI
的对象的 GoogleSheetsAPI
GoogleSheetsAPI googleSheetsAPI = new GoogleSheetsAPI(spreadsheetId, credentiialsFile);
The constructor must not have void
, it should be: 构造函数不能包含
void
,它应该是:
public GoogleSheetsAPI(String spreadsheetId, String credentialsFile) throws Exception {
this.spreadsheetId = spreadsheetId;
this.credentialsFile = credentialsFile;
service = getSheetsService();
}
构造函数没有任何返回类型...因为这是一种特殊方法,如果您定义自己的构造函数,则不要定义空构造函数,因为jvm提供了默认值...
Class.newInstance invokes the no-arg constructor Class.newInstance调用no-arg构造函数
Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);
Object o = cons.newInstance("JLabel"); 对象o = cons.newInstance(“ JLabel”);
to invoke a different constructor, you need to use the reflection package (java.lang.reflect). 要调用其他构造函数,您需要使用反射包(java.lang.reflect)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.