黑马程序员技术交流社区
标题:
看看如何用java的反射技術
[打印本页]
作者:
bluesliumile
时间:
2017-2-17 21:22
标题:
看看如何用java的反射技術
package myprojectTest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class PathClassLoader extends ClassLoader {
protected final ClassLoader parent;
private final Hashtable<String,Class<?>> definedClass = new Hashtable<String,Class<?>>();
public PathClassLoader(){
this(PathClassLoader.class.getClassLoader());
}
public PathClassLoader(ClassLoader parent){
this.parent = parent;
}
protected synchronized Class loaderClass(String name,boolean resolve)throws ClassNotFoundException{
Class<?> cls = findLoadedClass(name);
if(cls == null && parent != null){
try{
cls = parent.loadClass(name);
}catch(ClassNotFoundException e){
}
}
if(cls == null){
cls = findClass(name);
}
if(resolve){
resolveClass(cls);
}
return cls;
}
public Class<?> loadClass(File file) throws ClassNotFoundException,IOException{
return loadClass(new FileInputStream(file));
}
public Class<?> loadClass(InputStream in) throws ClassNotFoundException,IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int l;
for(;;){
l= in.read(buf);
if(l <= 0){
break;
}
out.write(buf, 0, l);
}
in.close();
return loadClass(out.toByteArray());
}
public Class<?> loadClass(byte[] b) throws ClassNotFoundException{
return loadClass(b,0,b.length);
}
public Class<?> loadClass(byte[] b,int off, int len) throws ClassNotFoundException{
Class<?> cls = defineClass(null,b,off,len);
definedClass.put(cls.getName(), cls);
return loadClass(cls.getName());
}
protected Class<?> findClass(String name) throws ClassNotFoundException{
Class<?> cls = definedClass.get(name);
if(cls == null){
throw new ClassNotFoundException(name);
}else{
return cls;
}
}
public void loadDirectory(File dir) throws ClassNotFoundException ,IOException{
if(dir.isFile()){
if(dir.getName().endsWith("class")){
loadClass(dir);
}
return;
}else{
for(File file: dir.listFiles()){
if(file.isDirectory()){
loadDirectory(file);
}else{
if(file.getName().endsWith("class")){
loadClass(file);
}
}
}
}
}
public static Method[] findClassAllMethod(Class<?> want){
Method[] lookup = want.getDeclaredMethods();
System.out.println("类:"+want.getName()+"的方法共有"+lookup.length+".");
StringBuffer methodName = new StringBuffer();
for (int i = 0; i < lookup.length; i++) {
System.out.println(getMethodName(i,methodName,lookup[i]));
methodName.delete(0, methodName.length());
}
return lookup;
}
public static String getMethodName(int i,StringBuffer methodName,Method currentMethod){
methodName.append("方法")
.append(i)
.append(":")
.append(currentMethod.getReturnType().toString())
.append(" ")
.append(currentMethod.getName())
.append("(");
Class<?>[] parameterTypes = currentMethod.getParameterTypes();
if(parameterTypes.length != 0){
for (int j = 0; ; j++) {
methodName.append(parameterTypes[j].toString());
if(j == parameterTypes.length -1){
break;
}
methodName.append(",");
}
}else{
methodName.append(")");
return methodName.toString();
}
methodName.append(")");
return methodName.toString();
}
public static Boolean doAction(String className,PathClassLoader dc){
Boolean flag = true;
Class<?> want;
try{
want = dc.findClass(className);
if(want == null){
flag = false;
}
else{
Method[] lookup = findClassAllMethod(want);
doWhatMethod(lookup,want);
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}
/*
* Object my = want.newInstance();
* Method action = want.getDeclaredMethod("moveRight",int.class);
* action.invoke(my,2);
* if(want != null){
* System.out.println("I want nobody but you");
* }
*/
return flag;
}
public static void doWhatClassMessage(){
System.out.println("*******************");
System.out.println("提示:");
System.out.println("请输入操作的类的名字:");
System.out.println("输入bye退出");
}
public static void doWhatClass(PathClassLoader dc){
doWhatClassMessage();
Scanner sc = new Scanner(System.in);
do{
try{
if(sc.hasNext()){
String className = sc.next();
if(className.equals("bye")){
break;
}else{
if(!doAction(className,dc)){
System.out.println("没有找到该类"+className);
}
continue;
}
}
}catch(Exception e){
System.out.println("你输入的类的信息有误");
e.printStackTrace();
continue;
}
}while(true);
}
public static int getIntParameter(){
int parameter = 0;
Scanner sc = new Scanner(System.in);
do{
if(sc.hasNextInt()){
parameter = sc.nextInt();
System.out.println("int的parameter为:"+parameter);
break;
}else{
System.out.println("你输入的参数数据有问题,请重新输入");
}
}while(true);
return parameter;
}
public static String getStringParameter(){
String parameter = null;
Scanner sc = new Scanner(System.in);
parameter = sc.next();
return parameter;
}
public static void doWhatMethodMessage(){
System.out.println("***********************************");
System.out.println("提示(目前只能执行基本数据类型的参数的方法):");
System.out.println("请输入调用方法的序号:");
System.out.println("输入back返回");
System.out.println("***********************************");
}
public static void doWhatMethod(Method[] lookup,Class<?> want){
do{
doWhatMethodMessage();
Scanner sc = new Scanner(System.in);
try{
if(sc.hasNextInt()){
int i = sc.nextInt();
System.out.println("获取方法");
System.out.println(getMethodName(i,new StringBuffer(),lookup[i]));
Class<?>[] parameterTypes = lookup[i].getParameterTypes();
Object myObject = want.newInstance();
Object[] parameter = new Object[parameterTypes.length];
for (int j = 0; j < parameter.length; j++) {
System.out.println("请输入参数"+j);
System.out.println("参数类型:"+parameterTypes[j].getName());
if(parameterTypes[j].getName().equals("int")){
parameter[j] = getIntParameter();
}
if(parameterTypes[j].getName().equals("String")){
parameter[j] = getStringParameter();
}
}
System.out.println("开始执行方法*******");
lookup[i].invoke(myObject, parameter);
System.out.println("执行方法完毕*******");
}
if(sc.hasNext()){
String bye = sc.next();
if(bye.equals("back")){
break;
}
}
}catch(Exception e){
System.out.println("你输入的数据有误");
e.printStackTrace();
continue;
}
}while(true);
}
public static void printClassName(Object obj){
System.out.println("The Class of " + obj + "is" + obj.getClass().getName());
}
public static void main(String[] args) {
PathClassLoader dc = new PathClassLoader();
//URL[] urls;
try{
dc.loadDirectory(new File("C:\\eclipseWork\\Proxy\\bin"));
Set<String> key = dc.definedClass.keySet();
Iterator<String> it = key.iterator();
String className;
while(it.hasNext()){
className = it.next();
System.out.println(className);
}
doWhatClass(dc);
}catch(Exception err){
System.err.println(err);
}
}
}
作者:
bluesliumile
时间:
2017-2-17 21:23
弄啥,都要弄一點
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2