Java 有没有办法向接口添加默认构造函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22810921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:04:04  来源:igfitidea点击:

is there a way to add a default constructor to an interface

javagenericsjava-8default-method

提问by Joshua Kissoon

With default methods now added to Java 8, is there any way to create a default constructor?

现在 Java 8 中添加了默认方法,有没有办法创建默认构造函数?

I've tried:

我试过了:

public interface KadContent<T>
{
    public default KadContent()
    {

    }
...

Getting the error <identifier> expectedfrom Netbeans

<identifier> expected从 Netbeans获取错误

Why Needed?I'm using Gson to serialize the objects and getting the "unable to invoke no-args constructor .." error and I do know that I can resolve this problem using Gson's InstanceCreator. But is there a way to create a default Constructor?

为什么需要?我正在使用 Gson 来序列化对象并收到“无法调用无参数构造函数..”错误,我知道我可以使用 Gson 的InstanceCreator解决这个问题。但是有没有办法创建一个默认的构造函数?

Update

更新

I've found the problem with my own code. I was using

我发现我自己的代码有问题。我正在使用

gson.fromJson(new String(data), InterfaceName.class);

instead of

代替

gson.fromJson(new String(data), ClassName.class);

So even though the subclass had default constructors, the deserialization code was incorrect. But the question of default constructor still stands.

因此,即使子类具有默认构造函数,反序列化代码也是不正确的。但是默认构造函数的问题仍然存在。

采纳答案by thobens

No, this is not possible.

不,这是不可能的。

  1. It does not make sense in an interface
  2. If you implement an interface, the class has already a default constructor (the one without arguments)
  1. 它在界面中没有意义
  2. 如果你实现了一个接口,这个类已经有一个默认的构造函数(没有参数的那个)

You may want to use an abstract class if you want implementations have a "default constructor".

如果您希望实现具有“默认构造函数”,您可能需要使用抽象类。

回答by AlexWien

It does not make sense to provide an Constructorin an Interface.

提供Constructorin 是没有意义的Interface

Check if it makes sense for you to provide a default initialize()method instead.

检查您是否可以提供默认initialize()方法。

回答by MTilsted

You need to add the default constructor to the class you want to serialize.

您需要将默认构造函数添加到要序列化的类。

回答by codeMan

Constructors are when the objects come into picture and the fact that a object for an interface cannot be constructed is SOUND, be it Java, C# or Java8

构造函数是当对象出现并且无法构造接口的对象这一事实是合理的,无论是 Java、C# 还是 Java8

So... if you have any functionality that you would want to define by default in the interface level, Java8 introduces the concept of Default Methods.

所以...如果您想在接口级别默认定义任何功能,Java8 引入了Default Methods的概念。

回答by alexsalo

Yes, kind of! You can do:

是的,有点!你可以做:

public interface MyInterface {
  MyInterface NO_OP = new MyInterface() {};
}