使用反射创建对象而不是调用类构造函数会导致任何显着的性能差异吗?
如何动态循环遍历java中的类属性.
例如:
public class MyClass{
private type1 att1;
private type2 att2;
...
public void function(){
for(var in MyClass.Attributes){
System.out.println(var.class);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这在Java中可能吗?
我一直试图理解使用new实例化对象与使用之间的区别Class.forName("A").newInstance();.
我已经为一个简单的类运行了以下代码,该类A显示使用Class.forname("A").newInstance()比使用just的速度慢70-100倍new A().
我很想知道为什么会有这么大的时间差异,但无法弄清楚.请有人帮我理解原因.
public class Main4test {
public Main4test() {
}
static int turns = 9999999;
public static void main(String[] args) {
new Main4test().run();
}
public void run() {
System.out.println("method1: " + method1() + "");
System.out.println("method2:" + method2() + "");
}
public long method2() {
long t = System.currentTimeMillis();
for (int i = 0; i < turns; i++) {
try {
A a = (A) Class.forName("A").newInstance();
} catch (InstantiationException …Run Code Online (Sandbox Code Playgroud) 我知道使用javassist的反射的替代方法,但是使用javassist有点复杂。而且由于lambda或koltin中的某些其他功能,javassist有时不能很好地工作。因此,还有其他方法可以不使用反射来迭代数据类的所有字段。
我找到按钮有问题.我有一个AlertDialog选择5种选择之一的地方.当我选择一个选项时,我想改变我点击的按钮的颜色.我在xml文件里面声明了按钮<RealativeLayout>但是当我试图通过id找到我的按钮时(id's就像"id1","id2"...)使用这个findViewById方法,有一个错误,它说我不能像我一样使用这个方法:
AlertDialog.Builder builder = new AlertDialog.Builder(StartGameActivity.this);
builder.setTitle(R.string.pickColor);
builder.setItems(R.array.colorArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Button btn_tmp;
String theButtonId = "id";
theButtonId = theButtonId+(String.valueOf(which));
btn_tmp = (Button) findViewById(theButtonId);
}
});
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题,或者我应该使用其他方法?
编辑:
我想我解决了我的问题.我使用了Button的方法之一:getId(),如下所示:
final int id = clickedButton.getId();
final ImageButton btn_tmp;
btn_tmp = (ImageButton)findViewById(id);
Run Code Online (Sandbox Code Playgroud) 编辑2:具有完全object-oriented实现的程序是否具有高性能?大多数framework都是用它的全部功能编写的.然而,reflection也被大量用于实现它,因为AOP和dependency injection.使用reflection会在一定程度上影响性能.
那么,使用它是好的做法reflection吗?是否有一些替代编程语言结构的反射?应该reflection在多大程度上使用?
是否可以构造一个List<Object>其中元素是未实例化的类,目的是获取列表元素之一并从该类运行静态方法或实例化该类的新实例?另外,如何才能做到这一点以及这样做有多不可取(以及为什么)?
添加一些上下文:我想创建一个生成随机城市的应用程序,将建筑物放置在城市中,其中每个建筑物都是许多建筑物类之一的实例,每个建筑物类都继承自一个抽象基类。为了选择适合某块土地的建筑物,程序可能会迭代所有可能的建筑物类别的列表,检查是否可以满足该建筑物所需的参数(最小/最大高度、占地面积、形状等)或这些类可以以某种其他方式存储,可能使用映射或某些其他结构。最重要的是我需要存储(引用?)到未实例化的类。
java ×6
reflection ×3
android ×1
attributes ×1
bytecode ×1
class ×1
coding-style ×1
kotlin ×1
loops ×1
optimization ×1
performance ×1