问题描述
现在将默认方法添加到Java 8中,有没有办法创建默认构造函数?
With default methods now added to Java 8, is there any way to create a default constructor?
我试过:
public interface KadContent<T>
{
public default KadContent()
{
}
...
获取错误< identifier>来自Netbeans的预期
为什么需要?我正在使用Gson序列化对象并获得无法调用no-args构造函数..错误,我知道我可以使用Gson的。但有没有办法创建默认的构造函数?
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?
更新
我用我自己的代码发现了问题。我正在使用
I've found the problem with my own code. I was using
gson.fromJson(new String(data), InterfaceName.class);
而不是
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.
推荐答案
不,这是不可能的。
- 在界面中没有意义
- 如果你实现了一个接口,那么这个类有已经是默认构造函数(没有参数的构造函数)
如果希望实现具有默认构造函数,则可能需要使用抽象类。
You may want to use an abstract class if you want implementations have a "default constructor".
这篇关于有没有办法将默认构造函数添加到接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!