1:获取class的方法
Class class1=Test.class;
Class<? extends Test> class2=new Test().getClass();
Class class3=Class.forName("com.包名.Test");
2:getMetohd(),getDeclaredMethod()的区别
import android.util.Log;
public class Test {
private String name;
private String age;
public Test() {
}
private Test(String name, String age) {
this.name = name;
this.age = age;
}
private void getAge(String age){
Log.d("Tag:", "getAge: 打印getAge方法:");
}
private void getName(String age){
Log.d("Tag:", "getName: 打印getName方法:");
}
public void getTest1(int s){
Log.d("Tag: ", "getTest1 方法: ");
}
public void getTest2(int a,int a2){
Log.d("Tag:", "getTest2 方法: ");
}
}
Method[] methods=class1.getMethods();
for (int i = 0; i < methods.length; i++) {
Log.d(TAG, ""+methods[i]);
}
Method[] methods1=class1.getDeclaredMethods();
for (int i = 0; i < methods1.length; i++) {
Log.d(TAG, ""+methods1[i]);
}
分别打印:
public static transient java.lang.Object
public boolean java.lang.Object.equals(java.lang.Object)
public final java.lang.Class java.lang.Object.getClass()
public void com..switchcolor.Test.getTest1(int)
public void com..switchcolor.Test.getTest2(int,int)
public int java.lang.Object.hashCode()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public java.lang.String java.lang.Object.toString()
public final native void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public void com.switchcolor.Test.getTest1(int)
public void com.switchcolor.Test.getTest2(int,int)
private void com.switchcolor.Test.getAge(java.lang.String)
private void com.switchcolor.Test.getName(java.lang.String)
getMetohd()获取该类以及其父类的所有public方法。
getDeclaredMethod()获取该类的所有方法
3:获取类方法
public 方法
Class class1=Class.forName("com.包名.Test");
Method method=class1.getMethod("getTest1",int.class);
method.invoke(class1.newInstance(),5);
private方法:
Method method1=class1.getDeclaredMethod("getName", String.class);
method1.setAccessible(true);
method1.invoke(class1.newInstance(),"s");
多参时:
Class[] args = new Class[1];
args[0] = String.class;
Object[] objects = new Object[1];
objects[0] = "nisdff";
try {
Object testClass = Class.forName("com.guoxw.switchcolor.Test").newInstance();
Method method = testClass.getClass().getDeclaredMethod("getName", args);
method.setAccessible(true);
method.invoke(testClass, objects);
} catch (Exception e) {
Log.d("Tag:", "onCreate: " + e.toString());
}