有没有办法实现通用 class 来显示对象字段?
Is there a way to implement a generic class for displaying an object fields?
我有一些 classes(例如医院、医生、护士等),我需要编写一个通用 class 将不同类型的对象附加到文件。每个class一个显示其字段的方法,但我无法通过此错误"Cannot resolve method 'print' in T"
这是代码:
package Service;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileService<T>
{
private static WriteFileService instance;
private WriteFileService(){}
public static WriteFileService getInstance()
{
return instance;
}
public void appendObject(T object, String fileName)
{
try {
File file = new File(fileName);
// creates the file if it does not exist
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file, true); // append mode = true
BufferedWriter bufferedWriter = new BufferedWriter(fw);
object.print(bufferedWriter); //! ERROR: Cannot resolve method 'print' in T
bufferedWriter.flush();
bufferedWriter.close();
}
catch(IOException e)
{
System.out.println("Problem handling the files!");
e.printStackTrace();
}
}
}
任何有关该方法的帮助都会有所帮助
由于类型擦除,您的 T 被视为对象(在运行时)并且对象 class 中没有 print()
方法。
您可以添加接口:
public interface Printable {
void print();
}
并让所有 classes 实施它。
然后你需要改变这个:
public class WriteFileService<T>
对此:
public class WriteFileService<T extends Printable>
我有一些 classes(例如医院、医生、护士等),我需要编写一个通用 class 将不同类型的对象附加到文件。每个class一个显示其字段的方法,但我无法通过此错误"Cannot resolve method 'print' in T"
这是代码:
package Service;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileService<T>
{
private static WriteFileService instance;
private WriteFileService(){}
public static WriteFileService getInstance()
{
return instance;
}
public void appendObject(T object, String fileName)
{
try {
File file = new File(fileName);
// creates the file if it does not exist
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file, true); // append mode = true
BufferedWriter bufferedWriter = new BufferedWriter(fw);
object.print(bufferedWriter); //! ERROR: Cannot resolve method 'print' in T
bufferedWriter.flush();
bufferedWriter.close();
}
catch(IOException e)
{
System.out.println("Problem handling the files!");
e.printStackTrace();
}
}
}
任何有关该方法的帮助都会有所帮助
由于类型擦除,您的 T 被视为对象(在运行时)并且对象 class 中没有 print()
方法。
您可以添加接口:
public interface Printable {
void print();
}
并让所有 classes 实施它。 然后你需要改变这个:
public class WriteFileService<T>
对此:
public class WriteFileService<T extends Printable>