常用方法使用未知对象类型java

时间:2017-05-12 17:52:51

标签: java generics inheritance interface

我正在编写一些java代码,我不确定应该使用什么结构。我有不同的类,每个类都包含一个populate方法,从文本文件接收一行文本。文本文件的内容特定于类。我需要修改方法(如下所示),以便它读取特定的文本文件,然后使用文本文件中的数据填充正确的类(对象)。读取文本文件(如下所示)的方法是相同的,无论它将填充哪个未知对象,除了对象类型。

Public Class ReceivesMyTextFile{
    /*This class receives my text file and does some other stuff. */

    /*Common method.  I do not want to put this readData method, which is 
      the same except one line of code, into each of my UnknownUntilRunTime 
      classes. */
    public void readData(File inFile){

        /* the contents of inFile determine which UnknownUntilRunTime class
          to instantiate, and then call its populate method in the loop. */

        /* I do not want to instantiate this object in the loop, but I can't 
           do it here either because I don't know what type it is yet. */
        UnknownUntilRunTime unknownObject = new UnknownUntilRunTime();

        //TextFileReader handles reading one line of text at a time using 
        //BufferedReader class.
        TextFileReader tfr = new TextFileReader(inFile.getPath());

        String currentRecord = tfr.getNextLine();
        while(tfr.hasData()){
            currentRecord = currentRecord.trim();

            //This is the problem.  I don't know this object until run-time
            //The contents of inFile determines the object type.
            //this is the only line of code different.
            unknownObject.populate(currentLine);

            currentRecord = tfr.getNextLine();
        }
    }
}

Public Class UnknownUntilRunTime{
    /* this class represents one of many different types of products.  
       this class is unknown until the contents of the correlating text file 
       are read. */


    public void populate(String currentLine){ 

        //populate this object with data from each currentLine of text. 

    }
}

我的问题是如何在不知道对象类型的情况下如何组织我的代码来调用这个常用方法?也许我应该以不同的方式做到这一点?这是使用继承,接口或泛型的示例吗?我只是不确定如何继续。任何一个例子的建议将不胜感激!谢谢!

1 个答案:

答案 0 :(得分:2)

  

我的问题是如何组织我的代码来调用它   常用方法,不知道对象类型?

您有多种对象,其populate()方法应以String作为参数。
使用populate(String)方法的界面应该符合您的需要。

声明一个接口:Populatable并创建应该填充Populatable的实现的对象。

public interface Populatable{   
  void populate(String line);
}

实施:

public MyObject implements Populatable{
     public void populate(String line){
          // do task...
     }
}

现在你可以在你的方法中使用它们了:

 // you declare the interface as declared type and the chosen implementation 
 // is determined at runtime according to your requirements
Populatable populatable = ...; 

while(tfr.hasData()){
    currentRecord = tfr.getNextLine();
    currentRecord = currentRecord.trim();
    populatable.populate(currentLine);
}

PS:我已经颠倒了指令的顺序,因为在获取记录之前修剪记录似乎不合逻辑。