簡體   English   中英

無法使用Java中的參數化構造函數實例化對象

[英]Unable to instantiate an object using parameterized Constructor in java

這是我要實例化的課程:

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 googleSheetsAPI = new GoogleSheetsAPI(spreadsheetId, credentiialsFile);

在此處輸入圖片說明

構造函數不能包含void ,它應該是:

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

構造函數沒有任何返回類型...因為這是一種特殊方法,如果您定義自己的構造函數,則不要定義空構造函數,因為jvm提供了默認值...

Class.newInstance調用no-arg構造函數

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

對象o = cons.newInstance(“ JLabel”);

要調用其他構造函數,您需要使用反射包(java.lang.reflect)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM