java

g52tjvyc  于 2021-06-04  发布在  Hadoop
关注(0)|答案(2)|浏览(377)
public class classifyTweet {

  public static class MapClass 
          extends Mapper<LongWritable, Text, Text, Text> {

  static final Configuration conf = new Configuration();

  protected void map(LongWritable key, Text value, Context context) 
             throws IOException, InterruptedException {

  StandardNaiveBayesClassifier classifier = new StandardNaiveBayesClassifier(NaiveBayesModel.materialize(new Path(modelPath), conf));

    }
  }
 }

我只想初始化分类器变量一次,materialize方法抛出ioeception,如果我在map方法外声明它,就像配置对象初始化一样,会产生ioexception的编译错误。如何只初始化一次?

qlvxas9a

qlvxas9a1#

使标准化bayesclassifier-singleton

public class StandardNaiveBayesClassifier {
private static StandardNaiveBayesClassifier instance;

public static StandardNaiveBayesClassifier getInstance(... you params) {
    if (instance == null)
        instance = new StandardNaiveBayesClassifier();
    return instance;
}

private StandardNaiveBayesClassifier() {
}

}

mzmfm0qo

mzmfm0qo2#

您可以使用静态块来初始化 classifier 变量只有一次。

public class classifyTweet {

  public static class MapClass 
          extends Mapper<LongWritable, Text, Text, Text> {

  static final Configuration conf = new Configuration();

  static final StandardNaiveBayesClassifier classifier;

  static {
      try {
       classifier = new StandardNaiveBayesClassifier(NaiveBayesModel.materialize(new Path(modelPath), conf));
      }
      catch(IOException e) {
          e.printStackTrace();
          System.out.println("Initialization failed.");
      }
  }

  protected void map(LongWritable key, Text value, Context context) 
             throws IOException, InterruptedException {

  //do some work...

    }
  }
 }

我假设 modelPath 创建 classifier 静态块中的对象。你什么都别说。

相关问题