【问题标题】:Why can't I call a static method in the constructor of a class?为什么不能在类的构造函数中调用静态方法?
【发布时间】:2012-08-30 03:40:59
【问题描述】:

显然我的 Java 暂停时间太长了……

我有以下课程:

public class TimeLine {

    public static final String TIME_LINE_DATE_FORMAT = "dd.MM.yyyy";


    public TimeLine(Context context, LinearLayout layout)
    {
        this.context = context;
        this.layout = layout;           
    }

    // some methods and stuff

    public static Date getDateFromString(String dateString)
    {
        SimpleDateFormat s = new SimpleDateFormat(TIME_LINE_DATE_FORMAT);
        try {
            return s.parse(dateString);
        } catch (ParseException e) {            
            e.printStackTrace();
            return null;
        }
    }
}

我经常使用将字符串解析为日期,这就是为什么我希望这个函数只使用 1 次并且是静态的。

我尝试这样访问它:

public class TrackedValue {

    private double value;
    private String unit;
    private Date date;

    public TrackedValue()
    {       
    }

    public TrackedValue(Date date, String unit, double value)
    {
        this.date = date;
        this.unit = unit;
        this.value = value;
    }

    public TrackedValue(String dateString, String unit, double value)
    {      
        this.date = TimeLine.getDateFromString(dateString); //Here's the error
        this.unit = unit;
        this.value = value;
    }

    // some getters and setters here

}

这给我带来了错误: 方法 getDateFromString(String) 没有为类型时间线定义

呃……为什么?

【问题讨论】:

  • 我的猜测:你指的不是你认为的TimeLine
  • 或者可能是TimeLine没有编译
  • TimeLine 的方式不是编译。除此之外,代码没有其他问题。调用静态方法就好了。
  • TrackedValue.java 文件中的导入语句对于 Timeline 包是什么样的?

标签: java methods static constructor undefined


【解决方案1】:

查看您的导入部分。

你的时间线类是在那里引用的,还是你已经导入到应用程序的其他 jar 中的另一个?

【讨论】:

  • TrackedValue 导入看起来像这样:import java.text.SimpleDateFormat; import java.util.Date; import android.util.Log; import at.antonio.mytracker.graph.TimeLine; ... 所以它是我的。它只是在另一个包中
【解决方案2】:

Why can't I call a static method in the constructor of a class?

您可以在构造函数中调用静态方法,除非您没有访问修饰符限制等方法的访问权限,否则没有人可以阻止您。

您的import 语句可能有问题。请检查TimeLine 类是否存在或是否正确导入。

【讨论】:

    【解决方案3】:

    dah...TimeLine 没有保存,因此没有编译...我现在觉得有点愚蠢:-/ 谢谢大家!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-07
      • 2015-12-08
      • 1970-01-01
      • 2014-07-21
      • 2020-11-01
      • 2018-09-25
      • 2011-09-24
      • 2011-12-08
      相关资源
      最近更新 更多