读取父类中的子类变量

时间:2012-04-09 18:15:00

标签: java

我正在尝试访问父类中的子类变量。你可以建议我如何继续 基于以下代码片段?

public abstract class Base{

//some abstract methods
//one more method to parse the xml
    public final void parseXml(){
        String clName = Thread.currentThread().getStackTrace()[1].getClassName(); //child class name
        if(xmlFile_+clName){ //i am trying to access "Test.xmlFile_Test",
          //execute the if string is available
        }

    }
}
public class Test extends Base{
    public static final String xmlFile_Test = "<Hello>sample</Hello>";
    public int execute(){
        parseXml(); //This should call  base class method
    }
}

我的错误步骤在哪里..这是伪造的代码,可能会帮助您回答

1 个答案:

答案 0 :(得分:2)

在Base类及其所有子类中创建一个名为getXMLFile()的方法

public class Base{
    protected String getXMLFile(){
        return "BaseXML";
    }

    public void foo(){
        if(getXMLFile() ....){
            ...
        }
    }
}

public class Test{
    @Override
    protected String getXMLFile(){
        return "TestXML";
    }
}