使用反射调用方法

时间:2016-01-26 21:46:10

标签: java android methods reflection invoke

我有两节课。我想调用" saveq" QuestionPicker.class中的方法。此方法将一些字符串保存到SharedPreferences中。我想从另一个类调用该方法,称为问题。 我想使用反射调用方法,但我的代码不起作用.. 我认为问题出在反思的某个地方,但我无法看到它。 有人能看到问题吗?感谢

这是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();
                }



            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

我同意@Joni - 什么不起作用?例如,下面的代码&#34; work&#34;。我从中移除了Androidness,但概念应该是相同的。

package com.company;

public class QuestionPicker {
    public void saveq() {
        System.out.println( "saveq is called");
    }
}

package com.company;

import java.lang.reflect.Method;

public class Main {

public static void main(String[] args) {
        try {
            Class clazz = Class.forName("com.company.QuestionPicker");
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod("saveq");
            method.invoke(obj);
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
}