[英]Create an instance by a string name input
我正在开发 CS50 Android track Fiftygram 应用程序。 我的代码正在运行,但我不喜欢看到复制粘贴的代码。
当前检查下拉选定的项目名称并使用 if/else if 来调用表示转换的实例。 如何在不使用所有这些 if 和 else if 的情况下直接使用字符串调用 apply function。
如果我能找到办法,我可以修正一些措辞。 例如,我可以在调用 function 之前去掉字符串的 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);
}
}
我建议你创建一个方法并将filterList.getSelectedItem().toString()
变成一个变量。 然后利用反射创建一个 class
就像是
String item = filterList.getSelectedItem().toString();
apply(createInstance(item))
public Object createInstance(String item){
Class classDefinition = Class.forName(item);
return classDefinition.newInstance();
}
但是,如果该项目存在与否,您必须在那里添加进一步的验证。 但想法就是这样。 利用反射而不是使用新关键字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.