[英]How to convert a string to class Name and vice versa
I have a number of activities (Main1, Main2...Mainn) managed from a superClass so what I'm trying to do but fail is to Move from Main i to Main i+1 thru a button (nextPage), and in order not to repeat the same code n times I tried to convert the ClassName into Integer to get its number (i) and after that i concatenate that number (i+1) into a string and after that convert the string into Class type to call it from the Button (nextPage). 我有许多活动是由超类管理的(Main1,Main2 ... Mainn),所以我想做的但失败的是通过一个按钮(nextPage)从Main i移至Main i + 1,并按顺序进行不重复相同的代码n次,我尝试将ClassName转换为Integer以获得其数字(i),然后我将该数字(i + 1)连接为字符串,然后将字符串转换为Class类型以调用它从按钮(nextPage)。 here is the code : I edited my code an this is the solution that's working perfectly:
这是代码:我编辑了代码,这是运行良好的解决方案:
str = getClass().getName();// this code line converts the class name to string
int num = Integer.parseInt(str.substring(str.indexOf("_") + 1)); //this extracts integer from string
str1 = "com.example.Test.Main_" + (num + 1);//this is a pure concatenation
str2 = "com.example.Test.Main_" + (num - 1);//this is a pure concatenation
try {
nextClass = Class.forName(str1);// this how to convert string to a class name
i10.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), nextClass);
startActivity(i);
str = nextClass.getName();
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
查找Integer.parseInt(String)的文档:字符串中的字符必须全部为十进制数字 。
If you want to get the current class name you should use this: 如果要获取当前的类名,则应使用以下命令:
String str = getClass().getName();
Now str is Main1, Main2, ... . 现在str是Main1,Main2,...。 So you cannot parse it because it is not String.
因此您无法解析它,因为它不是String。 You can rename your classes with this format: Main_1, Main_2, ... and change your code :
您可以使用以下格式重命名您的类:Main_1,Main_2等,然后更改代码:
int num = Integer.parseInt(str.substring(str.indexOf("_") + 1));
str1="Main_"+(num+1);
Class nextClass=Class.forName("com.example.Test."+ str1);
Try this code. 试试这个代码。 should work
应该管用
String str = getClass().toString();
Integer num = Integer.parseInt(str.replaceAll("\\D+",""));
str1="Main"+ String.valueOf(num+1);
Class<?> nextClass;
try {
nextClass = Class.forName("com.example.Test" + str );
i10.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), nextClass);
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.