若不记得一个类是否有某个方法,或者不知道一个类究竟能做什么,则这个小工具就帮上忙了。
package December2016;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.regex.Pattern;
/**
* Created by Donald on 2016/12/14.
*/
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){
System.out.println(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){
System.out.println(
p.matcher(method.toString()).replaceAll("") //去掉 包名.类名.
);
}
for(Constructor ctor : ctors){
System.out.println(p.matcher(ctor.toString()).replaceAll("")); //去掉 包名.类名.
}
lines = methods.length + ctors.length;
}else{
for(Method method : methods){
if(method.toString().indexOf(args[1]) != -1){
System.out.println(p.matcher(method.toString()).replaceAll(""));
}
}
for(Constructor ctor : ctors){
if(ctor.toString().indexOf(args[1]) != -1){
System.out.println(
p.matcher(ctor.toString()).replaceAll("")
);
lines++;
}
}
}
}catch (ClassNotFoundException e){
System.out.println("No such class: " + e);
}
System.out.println("lines : " + lines);
}
}
一、配置args
凡凡使用的是IDEA,同时注意:包名