2013-06-24 29 views
0
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)); 

    } 
    } 
} 

我想只有一次初始化变量的分类,物化方法抛出IOEception,如果我声明它之外的地图方法和类似配置对象初始化它给IOException的编译错误。我怎样才能初始化它只有一次?静态类中的IO异常 - java的

+0

提供该异常的堆栈跟踪。 –

+0

在编译时出现错误..未报告IOException必须被捕获或抛出 –

回答

1

化妆StandardNaiveBayesClassifier - 单

public class StandardNaiveBayesClassifier { 
private static StandardNaiveBayesClassifier instance; 

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

private StandardNaiveBayesClassifier() { 
} 

}

1

您可以使用一个静态块只需一次初始化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对象时是在范围内。你什么都不说。

+0

没有工作得到相同的IOException,我猜是因为'NaiveBayesModel.materialize(new Path(modelPath),conf)'抛出IOException我必须捕获它或使用抛出,所以这个语句必须在非静态方法内? –

+0

@MahenderSingh是的。确实。我忘了将'try/catch'放在静态块中。更新了答案。 – dcernahoschi