[英]Pass java.lang.Object as Parameter
I know that passing a an Object is not a good practise. 我知道传递对象不是一个好习惯。 But in this case it seems the best solution to me.
但是在这种情况下,这似乎是我的最佳解决方案。
public void doSomething(final Object obj) {
// some code
...
if (obj instanceof InputStream) {
document = PDDocument.load((InputStream) obj);
} else if (obj instanceof File) {
document = PDDocument.load((File) obj);
} else {
throw new IllegalArgumentException("Argument must be an instance of " + InputStream.class.getName() + " or " + " " + File.class.getName() + ".");
// more code
...
}
}
An alternative solution would have more duplicated code (all the line before and after PDDocument.load(obj);
) 替代解决方案将具有更多重复的代码(
PDDocument.load(obj);
之前和之后的所有行)
public void doSomething(final InputStream obj) {
// some code
...
document = PDDocument.load(obj);
// more code
...
}
}
public void doSomething(final File obj) {
// some code
...
document = PDDocument.load(obj);
// more code
...
}
}
Due to the duplicated code I prefer the first solution. 由于代码重复,我更喜欢第一个解决方案。
Do you know any better solution to solve this problem? 您知道解决此问题的更好解决方案吗?
Pass in the result of 传递结果
PDDocument.load(specificallyTypedVariable)
as a parameter to the method. 作为方法的参数。
This assumes that // some code
isn't doing some kind of setup for the load
call. 假定
// some code
未对load
调用进行某种设置。 If that's the case, you could pass in a Function<? super T, PDDocument>
如果是这样,您可以传入
Function<? super T, PDDocument>
Function<? super T, PDDocument>
along with the T
you're going to load it from: Function<? super T, PDDocument>
以及将要从中加载的T
:
public <T> void doSomething(final T obj, Function<? super T, PDDocument> loader) {
// some code
PDDocument document = loader.apply(obj);
// other code.
}
and invoke like: 并像这样调用:
doSomething(someFile, PDDocument::load);
doSomething(someInputStream, PDDocument::load);
Since PDDocument
can load from an InputStream
and you can obtain an InputStream
from a File
anyway, I'd suggest: 由于
PDDocument
可以从InputStream
加载,并且无论如何您都可以从File
获取InputStream
,所以建议:
public void doSomething(final InputStream in)
{
// some code
document = PDDocument.load(in);
// more code
}
public void doSomething(final File file)
{
try (
final InputStream in = new FileInputStream(file);
) {
doSomething(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Of course, handle errors accordingly! 当然,要相应地处理错误!
Also, I don't understand why you don't return the document
and put that processing in a method returning void
? 另外,我不明白为什么您不返回
document
并将该处理放入返回void
的方法中?
Move 移动
// some code
...
document = PDDocument.load(obj);
// more code
to a separate private
method which can only be called by the two above methods 到单独的
private
方法,只能由上述两个方法调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.