1.解释:
如果不知道某个对象的确切类型,可以通过RTTI获得,但是前提是在编译时,类型必须已知。但是,假设你获取了一个指向某个并不在你的程序空间中的对象的引用;即在编译时,你的程序根本无法获知这个对象所属的类。(例如,读取网络上一个文件的字符串,这个字符串是一个类名,要获取这个类的信息)。
想要在运行时获取类的信息的另一个动机,希望提供在跨网络的远程平台上创建和运行对象的能力。这称为“远程方法调用”(RMI)。
Class类和java.lang.reflect类库一起对反射的概念进行了支持。其实反射机制并没有什么神奇之处。RTTI和反射之间的真正区别只在于,对RTTI来说,编译器在编译时打开和检查.class文件。而对于反射机制来说,.class文件在编译期是不可获取的,所以是在运行时打开和检查.class文件。
想要在运行时获取类的信息的另一个动机,希望提供在跨网络的远程平台上创建和运行对象的能力。这称为“远程方法调用”(RMI)。
Class类和java.lang.reflect类库一起对反射的概念进行了支持。其实反射机制并没有什么神奇之处。RTTI和反射之间的真正区别只在于,对RTTI来说,编译器在编译时打开和检查.class文件。而对于反射机制来说,.class文件在编译期是不可获取的,所以是在运行时打开和检查.class文件。
getMethods()返回Method对象列表,getConstructors()返回Constructor对象列表。
实例:ShowMethods.java:
package net.pmpa.typeinfo;
import java.lang.reflect.*;
import java.util.regex.*;
import static net.mindview.util.Print.*;
public class ShowMethods {
private static String usage =
"usage:\n" +
"ShowMethods qualified.class.name\n" +
"To show all methods in class or:\n" +
"ShowMethods qualified.class.name word\n" +
"To search for methods involving 'word'";
private static Pattern p = Pattern.compile("\\w+\\.");
public static void main(String[] args) {
if(args.length < 1) {
print(usage);
System.exit(0);
}
int lines = 0;
try {
Class<?> c = Class.forName(args[0]);
Method[] methods = c.getMethods();
Constructor[] ctors = c.getConstructors();
if(args.length == 1) {
for(Method method : methods)
print(
p.matcher(method.toString()).replaceAll(""));
for(Constructor ctor : ctors)
print(p.matcher(ctor.toString()).replaceAll(""));
lines = methods.length + ctors.length;
} else {
for(Method method : methods)
if(method.toString().indexOf(args[1]) != -1) {
print(
p.matcher(method.toString()).replaceAll(""));
lines++;
}
for(Constructor ctor : ctors)
if(ctor.toString().indexOf(args[1]) != -1) {
print(p.matcher(
ctor.toString()).replaceAll(""));
lines++;
}
}
} catch(ClassNotFoundException e) {
print("No such class: " + e);
}
}
}