我正在尝试使用反射来使用MainActivity Class中的私有属性,但我不知道我做错了什么。有人可以帮忙吗?这是我的代码:MainActivity类和 这是我从异常中获得的错误: java.lang.IllegalArgumentException:object不是类的实例
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private Controller scheduleFor = new Controller();
private TextView display ;
private TextView title ;
OnClickListener monListener = new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
scheduleFor.handleRequest("monday");}};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
display = (TextView)findViewById(R.id.scheduleView);
title = (TextView)findViewById(R.id.day);
ImageButton monButton = (ImageButton)findViewById(R.id.monbutton);
monButton.setOnClickListener(monListener);
}
public void onStart(){
super.onStart();
display.setText("");
title.setText("Get your schedule");
}
}
public class MonHandler implements Handler {
private static final String TAG = "Scheduler";
@Override
public void handleIt(Object... args){
// TODO Auto-generated method stub
try{
Class<?> mainActivityClass = Class.forName("freesoft.nex.ec.MainActivity");
Field fDisplay = mainActivityClass.getDeclaredField("display");
Field fTitle = mainActivityClass.getDeclaredField("title");
fDisplay.setAccessible(true);
fTitle.setAccessible(true);
TextView dSchedule = (TextView) fDisplay.get(mainActivityClass);
TextView dTitle = (TextView)fTitle.get(mainActivityClass);
String schedule =
" 07h00 Breakfast\n" +
" 08h00 Department Metting\n" +
" 09h00 Class CIT 310\n" +
" 10h015 Class CIT 356\n" +
" 11h30 Class CIT 499\n" +
" 12h45 Lunch\n" +
" 14h00 Labs\n" +
" 17h00 Back home\n" +
" 21h00 F.H.E - ??\n";
String sDay = "Monday";
dSchedule.setText(schedule);
dTitle.setText("Schedule for " + sDay);
}catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d(TAG, "-->" + e);
}catch(NoSuchFieldException x){
x.printStackTrace();
Log.d(TAG, "-->" + x);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "--> " + e.getMessage());
Log.d(TAG, "--> " + e.getCause());
Log.d(TAG, "-->" + e.getLocalizedMessage());
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "-->" + e);
}
}
}
答案 0 :(得分:1)
问题似乎是您误解了Field
类中.get(...)
方法的用法。
TextView dSchedule = (TextView) fDisplay.get(mainActivityClass);
TextView dTitle = (TextView) fTitle.get(mainActivityClass);
您正在传递对类的引用,而是应该根据您看到的文档和异常提供该类型的正在运行的实例/对象。所以,你真正追求的是传递freesoft.nex.ec.MainActivity
的对象。现在,假设它实际上与您的代码所在的MainActivity
类相同,您可能需要做的就是将上述语句更改为:
TextView dSchedule = (TextView) fDisplay.get(MainActivity.this);
TextView dTitle = (TextView) fTitle.get(MainActivity.this);
请注意,您不能只提供this
,因为这将引用MonHandler
内部类的实例。