通过反射技术加载出Class里面的方法
public static void main(String[] args) throws Exception
{
// 参数:指定为目标类的路径
Class cls = Class.forName("af.test.Example");
Method[] methods = cls.getDeclaredMethods();
for(Method m : methods)
{
String name = m.getName();
Type type = m.getReturnType();
System.out.println(name + ", " + type.getTypeName());
}
}
//样例输出
/* test3, void
test5, double
test1, void
*/
通过反射技术创建一个实例
public static void main(String[] args) throws Exception
{
// 参数:指定为目标类的路径
Class cls = Class.forName("my.Student");
Object obj = cls.newInstance();
System.out.println("Exit.");
}
类的方法
public static void main(String[] args) throws Exception
{
//获取类
Class cls = Student.class;
Method[] methods = cls.getDeclaredMethods();
//遍历所有方法
for(Method m : methods)
{
//获取方法名
String name = m.getName();
//获取方法的类型
Class returnType = m.getReturnType();
//获取调用方法需要的类型
Class[] paramTypes = m.getParameterTypes();
//打印出来的方法的描述
System.out.print("- " + returnType.getSimpleName()
+ " " + name + "(");
for(int i=0; i<paramTypes.length; i++)
{
Class param = paramTypes[i];
System.out.print(param.getSimpleName());
if(i < paramTypes.length-1)
System.out.println(", ");
}
System.out.println(")");
}
System.out.println("Exit.");
}
/*
打印参考:
- Integer getId()
- void setName(String)
*/
获取一个方法
package my;
import java.lang.reflect.Type;
import af.test.Example;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test
{
public static Method getMethod(Method[] methods, String name)
{
for(Method m : methods)
{
if(m.getName().equals(name))
return m;
}
return null;
}
public static void main(String[] args) throws Exception
{
//从example.jar中加载一个类
Class cls = Class.forName("af.test.Example");
// 获取该类的方法
Method[] methods = cls.getDeclaredMethods();
// 按名称遍历查找 (要求没有重名的方法)
Method testMethod = getMethod(methods, "test1");
System.out.println("Exit.");
}
}