Java 子类强制在构造函数中调用 super() 的解决方法?
我正在编辑一个使用 RandomAccessFile 对象的程序,并且我想提出自己的 RandomAccessFile 类,该类使用除文件对象之外的不同数据源(它是 Amazon webservices S3 对象,但这无关紧要)
我想要基本上创建一个名为 RandomAccessS3 的类,该类以 RandomAccessFile 作为其超类,所以我可以简单地说
RandomAccessFile raf = new RandomAccessS3();
因此保持现有代码相同。我将简单地重写 RandomAccessFile 中的每个方法。
问题是,在子类 RandomAccessS3 的构造函数中,我被迫使用 super(file, mode) 调用 RandomAccessFile 的构造函数,该构造函数将文件名作为参数,如果文件无效,则会抛出错误并终止。
我无法用 try/catch 块包围 super() 调用,因为 super 需要成为构造函数中的第一行。我可以提供一个虚拟文件,但我不想强迫用户这样做。有什么简单的方法可以解决这个问题吗?
谢谢!
I am editing a program that uses a RandomAccessFile object, and I want to come up with my own RandomAccessFile class that uses a different source for the data other than a file object (it's an Amazon webservices S3 object, but that's irrelevant)
I want to basically make a class called RandomAccessS3 that has RandomAccessFile as its superclass, so I can simply say
RandomAccessFile raf = new RandomAccessS3();
and therefore keep the existing code the same. I will simply override every method in RandomAccessFile.
The problem is that in the subclass RandomAccessS3's constructor I am forced to call RandomAccessFile's constructor using super(file, mode) which takes as parameter a filename, and throws an error and dies if the file is invalid.
I can't surround the super() call with a try/catch block because super is required to be the first line in the constructor. I could supply a dummy file, but I don't want to force the user to do that. Is there any simple way around this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您实际上可以在超类上设置名称属性或其他内容。并在该类的构造函数中,将传入的 String 值设置为属于该类的 name 实例变量。
这样,所有派生类在实例化子实例时都必须传递一些内容,并且传递的值将推迟到父类。通过这种方式,您可以强制 super() 始终在导数中被调用。
well, you can actually set a name attribute or something on the super class. And in constructor of that class, set the value of the String passed in to the name instance variable belonging on that class.
This way all derivatives must pass in something while instantiating child instances and the value passed is deferred to the parent class. This way you can force super() to always be called in derivatives.
没有简单的方法可以解决这个问题。构造函数的作用是确保实例处于良好/有效的状态,而 RandomAccessFile 契约的一部分是实例链接到有效的文件。
作为一个巨大的黑客,我想你可以创建一个临时文件,只是为了满足 RandomAccessFile 构造函数。
更好的方法可能是创建一个新接口并将引用从 RandomAccessFile 更新到新接口。然后,实现该接口两次,一次使用 RandomAccessFile,一次使用 S3 调用。
There's no simple way around this. The constructor is there to make sure that an instance is in a good/valid state, and part of the contract of RandomAccessFile is that an instance is linked to a valid file.
As a huge hack, I suppose that you could create a temp file, just to satisfy the RandomAccessFile constructor.
A better approach probably is to create a new interface and update your references from RandomAccessFile to the new interface. Then, implement the interface twice, once using RandomAccessFile and once with S3 calls.