【问题标题】:Get a class dynamically动态获取类
【发布时间】:2014-12-20 07:18:09
【问题描述】:

我有一个 DataGridView 类,这是构造函数

//this class is created in the MainActivity 
public DataGridView(Context CTX,TableLayout Tl,int[] Weight) {
    this.CTX = CTX;
    this.Tl = Tl; 
    this.Weight= Weight;
}

我想添加一个接收类(无论是什么类)的参数,例如 MainActivity

public DataGridView(Context CTX,TableLayout Tl,int[] Weight,Class MA) {
    this.CTX = CTX;
    this.Tl = Tl; 
    this.Weight= Weight;
    //HERE
    this.MA = MA;
}

在 MainActivity 中执行此操作

public void Create(){
    int[] weight = new int[2];
    weight[0] = 1;
    weight[1] = 3;
    Dr= new DataGridView(CTX,Dt,weight,this);
    String[] Columnas = new String[2];
    Columnas[0] = "ID";
    Columnas[1] = "MATERIA";
    Dr.ColumnsAdd(Columnas);
}

我不想输入参数 MainActivity MA,因为我会向这个对象发送另一个活动。我想以动态方式获得它。

【问题讨论】:

  • 你想用这个动态类做什么?
  • 请注意,在 Java 中,我们不会以大写字母开头变量和方法名称。
  • 也许你想用this.getClass()调用构造函数?此外,您可能希望对 Class 类型进行参数化,例如 Class,或者任何你可以使用的“最高”类。另请参阅@pdegand59 和 maksimov 之前的 cmets。拜托,拜托,请按照马克西莫夫的建议去做。
  • 您为什么不将参数签名设置为“Activity ma”并传递您想要的任何 Activity?
  • 谢谢 maksimov,我是 java 新手。

标签: java android


【解决方案1】:

这是一个>link 解释如何使用反射在 Java 中动态加载或重新加载类。此外,您可能会发现这个post 很有用,并像这样应用它:

this.MA = Class.forName(MA.class.getName()).newInstance();

另外,你应该注意,如果你想使用它之前包含的内容,你必须按照第一个链接中的指示重新加载该类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多