-1
我有两个类。我想调用QuestionPicker.class中的“saveq”方法。此方法将一些字符串保存到SharedPreferences中。我想从另一个类调用该方法,即称为Questions。 我想调用使用反射的方法,但我的代码不起作用。 我认为这个问题是在反思的地方,但我看不到它。 有人可以看到问题吗?由于使用反射的调用方法
这里是QuestionPicker.class
public class QuestionPicker {
public void saveq() {
// MyApplication Class calls Context
Context context = MyApplication.getAppContext();
// Values to save
String Q1 = "SomeQuestion";
String Q2 = "SomeOtherQuestion";
String Q3 = "AndEvenMoreQuestions";
// Save the Strings to SharedPreferences
SharedPreferences.Editor editor = context.getSharedPreferences("QuestionsSaver", 0).edit();
editor.putString("Q1", Q1);
editor.putString("Q2", Q2);
editor.putString("Q3", Q3);
editor.apply();
}
}
这里是Questions.class
public class Questions extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
// storing string resources into Array
String[] subjects = getResources().getStringArray(R.array.subjects);
ListView lv = (ListView) findViewById(R.id.listView);
// Binding resources Array to ListAdapter
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, subjects);
lv.setAdapter(adapter);
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Invoke the saving Method
try {
Class cls = Class.forName("com.test.QuestionPicker");
Object obj = cls.newInstance();
Method method = cls.getMethod("saveq");
method.invoke(obj);
} catch(Exception ex){
ex.printStackTrace();
}
}
});
}
}
的方法 “saveq” 是公开的,什么是使用反射的原因是什么? –
我简化了一些类。我需要通过不同的变量名称来调用几个方法,这些方法来自Questions.class –
“不起作用”是什么意思? – Joni