当使用Java反射机制操作类成员时,传入对象的参数改成传入
null
package com.zuozuo.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class TestMain {
private static final String TAG = "VOICE_RECOG";
public static void main(String[] args) throws Exception {
// get static field
Class<?> clazz = Class.forName("com.zuozuo.test.TestMain");
Field fieldTag = clazz.getDeclaredField("TAG");
fieldTag.setAccessible(true);
String tag = (String)fieldTag.get(null); // null object 不要本着这道题不会但不能空着的思想new一个对象...
System.out.println("TAG is static ? " + Modifier.isStatic(fieldTag.getModifiers()));
System.out.println(tag);
// invoke static method
Method method = clazz.getDeclaredMethod("name", String.class);
String output = (String)method.invoke(null, "B"); // null object
System.out.println("name is static ? " + Modifier.isStatic(method.getModifiers()));
System.out.println(output);
}
public static String name(String input) {
if ("A".equals(input)) {
return "_A_";
}
return "_B_";
}
}