Java 反射调用

	public void getcontact2(View view) {

		try {
			//Class clazz = new ContactsLister().getClass();	//第一种		
			Class clazz=ContactsLister.class; //第二种
			//clazz.getMethod(name, parameterTypes)
			Method method = clazz.getDeclaredMethod("listContacts",
					Context.class, String.class);
			method.invoke(clazz, getApplicationContext(),null);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void getcontact3(View view) {

		try {
			 Class class1= Class.forName("com.example.getroot.ContactsLister");
		      Method method = class1.getMethod("listContacts",Context.class,String.class);
		      Object ret = method.invoke(class1,getApplicationContext(),"");
		      System.out.println("Results: " + ret);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
getMethod返回当前类和继承自父类的method
getDelaredMethod只返回当前类的method
getField和getDeclaredField也一样

相关链接:http://blog.csdn.net/stevenhu_223/article/details/9286121



你可能感兴趣的:(Java 反射调用)