【问题标题】:Unable to instantiate an object using parameterized Constructor in java无法在java中使用参数化构造函数实例化对象
【发布时间】:2017-07-21 05:25:28
【问题描述】:

这是我要实例化的类:

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();
}

}

这就是我创建类对象的方式 GoogleSheetsAPI

GoogleSheetsAPI googleSheetsAPI = new GoogleSheetsAPI(spreadsheetId, credentiialsFile);

【问题讨论】:

标签: java constructor compiler-errors


【解决方案1】:

构造函数不能有void,应该是:

public GoogleSheetsAPI(String spreadsheetId, String credentialsFile) throws Exception {
    this.spreadsheetId = spreadsheetId;
    this.credentialsFile = credentialsFile;
    service = getSheetsService();
}

【讨论】:

  • 这是我犯的错误。谢谢 Damian :) 构造函数没有空白。
【解决方案2】:

构造函数没有任何返回类型...因为是一种特殊的方法,如果您定义自己的构造函数,则不要定义空构造函数,因为jvm提供默认...

【讨论】:

    【解决方案3】:

    Class.newInstance 调用无参数构造函数

    Class<?> cl = Class.forName("javax.swing.JLabel");
    Constructor<?> cons = cl.getConstructor(String.class);
    

    对象 o = cons.newInstance("JLabel");

    要调用不同的构造函数,您需要使用反射包 (java.lang.reflect)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多