Java:使用泛型作为抽象层

标签 java generics

我正在尝试使用泛型作为抽象层,类似于Java集合。这是一个简化的示例:类 EmployeeRecord 存储有关员工的信息,类 Table 应该是通用的并且能够存储各种类型的数据。该类型作为泛型传递给 Table。 我在传递调用存储的特定类时遇到问题。

调用 print() 方法有什么问题? 怎么解决?

class EmployeeRecord
{
  String name;

  EmployeeRecord( String name )
  {
    this.name = name;
  }

  void print()
  {
    System.out.println( name );
  }
} 

class Table<Record>
{
  Record rec;

  void set( Record rec )
  {
    this.rec = rec;
  }

  void printAll()
  {
    rec.print(); // COMPILER ERROR
/*
Test.java:27: error: cannot find symbol
    rec.print();
       ^
  symbol:   method print()
  location: variable rec of type Record
  where Record is a type-variable:
    Record extends Object declared in class Table
1 error
*/
  }
} 

public class Test
{
  public static void main( String[] argv )
  { 
    EmployeeRecord emp = new EmployeeRecord("John");
    Table<EmployeeRecord> tab = new Table<EmployeeRecord>();
    tab.set( emp );
    tab.printAll();
  }
}

最佳答案

实现此目的的一种方法是创建所有记录类都将实现的通用接口(interface)

interface Record{
    void print();
}

那么你的EmployeeRecord类将如下所示

class EmployeeRecord implements Record
{
    String name;

    EmployeeRecord( String name )
    {
       this.name = name;
    }

    @Override
    public void print()
    {
        System.out.println( name );
    }
}

你的表格将如下所示

class Table<T extends Record>
{
    T rec;

    void set( T rec )
    {
        this.rec = rec;
    }

    void printAll()
    {
       rec.print(); 
    }
}

然后你从 main 方法中调用它,如下所示

public class Test {

    public static void main(String[] args) {
         EmployeeRecord emp = new EmployeeRecord("John");
         Table<EmployeeRecord> tab = new Table<EmployeeRecord>();
         tab.set( emp );
         tab.printAll();
    }
}

关于Java:使用泛型作为抽象层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711067/

相关文章:

Swift 协变泛型函数 : placeholder type is a subclass of another

java - Eclipse J 面向导 : How to create next page dynamically?

java.sql.SQLException : No suitable driver found for jdbc:mysql

java - 通用内部类构造函数接受不同类型的参数设置什么?

java - 如何计算文档集的词频?

forms - Delphi-TForm和泛型

Java 使用 Jconnect

java - 方法声明中的泛型

java - 使用泛型将子类构建器初始化为父构建器的类型

generics - [T; 之间有什么区别? N] 和 U 如果 U 总是设置为 [T; N]?