factory method pattern with class registration produces a nullpointer exception
well, i searched the internet to this problem but didn't find any proper solution
in http://www.oodesign.com/factory-pattern.html
the author described away to register classes using reflection or object creation
i tried the object creation approach by the following code: the factory class
package com.mf.egyptse;
import java.util.HashMap;
public abstract class ParserFactory {
private static HashMap parsers;
static
{
parsers= new HashMap();
System.out.println("This is first static block");
}
static void putParser(Object key,Object parser)
{
parsers.put(key, parser);
}
static Object getParser(Object key)
{
return parsers.get(key);
}
}
each parser register itself in the factory: public class NormalParser extends ParserFactory implements ParsingBehavior{
/**
* Define the number of nested columns or tags to be parsed
*/
final static int NO_OF_COLOUMNS = 13;
static String input = null;
static String[] elements= {"name","sector", "p.c", "open", "close", "chgpercent", "lastprice", "high", "low","value","volume","trades","marketcap"};
static
{
ParserFactory.putParser("normal", new NormalParser());
}
and the main is :
public class Main {
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// NileParser.parseNile();
// OTCParser.parseOTC();
// NormalParser.parseNormal();
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
the interface is:
package com.mf.egyptse;
import java.io.File;
import java.io.IOException;
public interface Pars开发者_高级运维ingBehavior {
void parseToXML(CharSequence input,File file) throws IOException;
}
this code return always nullpointer exception while executing. the porblem is that the static block don't executed. so what is the solution ?
As answered by "Snicolas", your problem is that the HashMap is not populated by the time its being used. Your static block in main should load all the necessary parser classes such that these classes register themselves first.
public class Main {
static {
// Load necessary parser classes
Class.forName("normal");
}
/**
* @param args
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
Getparser should return a ParsingBehavior. Cast inside it.
But your problem comes from the fact that your parser class is not loaded by the jvm, as it is not used by your main. So static code is not executed.
Your are mixing your factory with a bus. Let the main register your parser in the factory.
精彩评论