【问题标题】:Error by casting a class强制转换类时出错
【发布时间】:2017-07-19 20:38:16
【问题描述】:

我已经为全局变量创建了其他类,现在我只想这样转换它:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity1);
    class2 global;

    global = (class2)getApplicationContext();

我得到错误:

android.app.Application 无法转换为 eu.tools.test_training_home.class2

class2:

public class class2 extends Application {

    private String name="name1";
    private int number =0;

【问题讨论】:

  • 您正在尝试将对象从 Context 类转换为 Application 对象。这是可能的。
  • 对不起,我的意思是“不能”。
  • 我建议你遵循标准的 Java 命名约定,@Testiest。

标签: java class casting


【解决方案1】:

这里getApplicationContext() 返回一个Context 类的对象,但不返回class2

检查https://stackoverflow.com/a/907368/1435132

Custom global Application class breaks with "android.app.Application cannot be cast to"

【讨论】:

  • 在将构造函数添加到 class2 后出现错误:之前没有错误。
【解决方案2】:

问题是 Class2 中的构造函数 进入class2,我有1个构造函数,2个setter,2个getter 我已经删除了Constructor,然后错误没有出现

public class class2 extends Application {

private String name ="name1";
private int number =10;

public class2(String name, int number) { // this was the problem
    this.name = name;
    this.number = number;
}

public void setName(String name) {
    this.name = name;
}

public void setNumber(int number) {
    this.number = number;
}

public String getName() {
    return name;
}

public int getNumber() {
    return number;
}

}

【讨论】:

    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 2021-06-14
    • 2017-10-05
    • 1970-01-01
    • 2021-01-24
    相关资源
    最近更新 更多