简体   繁体   English

无法使用Java中的参数化构造函数实例化对象

[英]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.

相关问题 我如何通过将对象作为参数传递来实例化CDI bean,就像我从参数化构造函数中以普通Java实例化新对象一样? - How do I instantiate a CDI bean by passing an object as parameter just like I instantiate a new object in plain Java from a parameterized constructor? 在Java中使用参数化构造函数创建对象时出错 - Error while creating object using parameterized constructor in Java 如何在方法Java之外使用其构造函数实例化对象 - How to instantiate an object using it's constructor outside a method java Spring使用Java-Config(而非XML)使用构造函数争论实例化对象 - Spring instantiate object with constructor arguements using java-config (not XML) 无法通过java中的构造函数实例化对象 - failing to instantiate an object through a constructor in java 如何使用反射和Guava TypeToken实例化参数化类的Class对象 - How to instantiate a Class object for a parameterized class using reflection and Guava TypeToken Java实例化类的参数化类型 - Java instantiate class of parameterized type Spring-data-mongo 无法使用构造函数实例化 java.util.List - Spring-data-mongo unable to instantiate java.util.List using Constructor 无法在Java Servlet中实例化XSSFWorkbook的对象 - Unable to instantiate an object of XSSFWorkbook in Java servlet Java:如何在不使用父构造函数的情况下从子对象实例化父对象? - Java: How can I instantiate a parent object from child without using parent constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM