【问题标题】:Create an instance by a string name input通过字符串名称输入创建实例
【发布时间】:2020-08-08 19:04:14
【问题描述】:

我正在开发 CS50 Android track Fiftygram 应用程序。我的代码正在运行,但我不喜欢看到复制粘贴的代码。

目前正在检查下拉选择的项目名称,并使用 if/else if 来调用表示转换的实例。如何在不使用所有这些 if 和 else if 的情况下直接使用字符串调用 apply 函数。

如果我能找到办法,我可以修正一些措辞。例如,我可以去掉字符串的 Transformation 结尾,在调用函数之前自己添加。

public void applyFilter(View view) {
    if (filterList.getSelectedItem().toString() != null) {
        if (filterList.getSelectedItem().toString().equals("ToonFilterTransformation")) {
            apply(new ToonFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("SepiaFilterTransformation")) {
            apply(new SepiaFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("ContrastFilterTransformation")) {
            apply(new ContrastFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("InvertFilterTransformation")) {
            apply(new InvertFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("PixelationFilterTransformation")) {
            apply(new PixelationFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("SketchFilterTransformation")) {
            apply(new SketchFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("SwirlFilterTransformation")) {
            apply(new SwirlFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("KuwaharaFilterTransformation")) {
            apply(new KuwaharaFilterTransformation());
        }
        else if (filterList.getSelectedItem().toString().equals("VignetteFilterTransformation")) {
            apply(new VignetteFilterTransformation());
        }
    }
}

public void apply(Transformation<Bitmap> filter) {
    if (original != null) {
        Glide
                .with(this)
                .load(original)
                .apply(RequestOptions.bitmapTransform(filter))
                .into(imageView);
    }
}

【问题讨论】:

    标签: java android xml android-studio cs50


    【解决方案1】:

    我建议你创建一个方法并将filterList.getSelectedItem().toString() 变成一个变量。然后在创建类时使用反射

    类似

    String item = filterList.getSelectedItem().toString();
    
    apply(createInstance(item))
    
    public Object createInstance(String item){
      Class classDefinition = Class.forName(item);
      return classDefinition.newInstance();
    }
    

    但是如果该项目存在与否,您必须在那里添加进一步的验证。 但想法就是这样。利用反射而不是使用 new 关键字

    【讨论】:

    • 我不知道,但它不起作用。它需要铸造,但铸造也不起作用。
    • 你能粘贴你的答案吗
    猜你喜欢
    • 2014-06-04
    • 2019-06-25
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2014-05-07
    相关资源
    最近更新 更多