我是新來的泛型類型,並想知道如何正確地實現泛型類中的泛型接口,所以類型的確定將被延遲到當我實例化對象時這個泛型類。在泛型類中實現通用接口
我的代碼如下:
package org.processor.interfaces;
import org.filter.interfaces.IFile;
public interface ProcessorResult<T> {
public IFile getFile();
public String getProcessorName();
public Class<? extends Processor<T>> getProcessorClass();
public T getResult();
}
而且類,它實現該接口:
package org.processor.interfaces.impl;
import org.filter.interfaces.IFile;
import org.processor.interfaces.Processor;
import org.processor.interfaces.ProcessorResult;
public class ProcessorResultImpl<T> implements ProcessorResult<T> {
private T result;
private String processorName;
private IFile file;
public ProcessorResultImpl(T result) {
this.t = result;
}
@Override
public IFile getFile() {
return file;
}
@Override
public String getProcessorName() {
return processorName;
}
@Override
public Class<? extends Processor<T>> getProcessorClass() {
return null;
}
@Override
public T getResult() {
return t;
}
}
時,我想實例化這個類的對象的時刻是在方法返回ProcessorResult作爲(這僅僅是爲了示範):
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.filter.interfaces.IFile;
import org.processor.interfaces.Processor;
import org.processor.interfaces.ProcessorFilter;
import org.processor.interfaces.ProcessorResult;
public class ProcessorLineCountImpl<T> implements Processor<T> {
private ProcessorFilter<T> processorFilter;
private String name;
public ProcessorLineCountImpl() {
}
public ProcessorResult<T> process(IFile file) {
int count = 0;
try (Scanner sc = new Scanner(file.openInputStream())) {
while (sc.hasNext()) {
String word = sc.next();
if (word.indexOf("\\") == -1) {
count++;
}
}
return null;
}
return null;
@Override
public String getName() {
return name;
}
@Override
public void setFilter(ProcessorFilter<T> filter) {
this.processorFilter = filter;
}
在th在情況下,我得到語法錯誤:
Type mismatch: cannot convert from ProcessorResultImpl<Long> to
ProcessorResult<T>
問題:
- 它是如何能夠正確地完成爲我出出主意,但沒有找到對任何解決方案網頁。
- 延遲確定類型直到實例化對象是否是一種很好的方法?
感謝您的任何建議。
這並未完全沒有意義 - 如果它是* generic *,那麼你爲什麼要硬編碼一個'Long'? –
這個'process'方法在哪裏定義? –
'process'需要返回'ProcessorResult' –
4castle