求一个利用java反射的例子

kent4j 2009-10-09 08:37:37
不太理解反射的作用
...全文
220 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dyccsxg 2009-10-11
  • 打赏
  • 举报
回复
import java.lang.reflect.Method;

public class Test{

public static void main(String [] args){
try{
//实例化类
People obj=(People)Class.forName("People").newInstance();

Method method=null;
//调用setName(String name)方法
method=obj.getClass().getMethod("setName",new Class[]{String.class});
method.invoke(obj,new Object[]{"princess"});
//调用getName()方法
method=obj.getClass().getMethod("getName");
String result=(String)method.invoke(obj);

System.out.println("result is : "+result);
}catch(Exception e){
}
System.out.println("...ok...");
}
}
class People {
private String name;

public People(){
name="no name";
}
public People(String name){
this.name=name;
}
//--get set methods--
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
}
amdgaming 2009-10-09
  • 打赏
  • 举报
回复
学习,看看
rookie001 2009-10-09
  • 打赏
  • 举报
回复
我也贴个,以前写的一个小作业,利用java提供的反射机制得到用户在程序运行时输入的类名,输出该类所在继承体系中的所有类中定义的方法,所有方法需按字母排序。
import java.lang.reflect.*;
import java.util.*;
import java.io.*;
/**
* PrintMethods class
* 本类利用java的反射机制,获取某个类继承体系的所有方法,按字母排序显示
* printAll,printMethods方法均可以静态调用
*/
public class PrintMethods {
//打印某个类的整个体系的所有方法
public static void printAll(String className){
try{
Class c = Class.forName(className);
System.out.println("******************Methods*******************\n");
while(c!=null){
printMethods(c.getName());
c = c.getSuperclass(); //得到本类的超类
}
System.out.println("\n");
}catch(ClassNotFoundException e){
System.out.println(e.toString());
}
}
/**
* 打印某类的所有方法
* 利用反射机制
* @param className类名
*/
public static void printMethods(String className){
try{
Class classTemp = Class.forName(className);
Method [] method = classTemp.getMethods(); //得到类的方法
Method methodTemp = null;
TreeMap<String,Method> tm = new TreeMap<String,Method>(); //TreeMap:方法名为key,方法为value
for(int i=0;i<method.length;i++){
tm.put(method[i].getName(), method[i]); //TreeMap 的初始化,再迭代打印即为字母排序
}
System.out.println("\n*********************************************************************");
System.out.print("\nMethods of the class "+className+":");
Iterator<Method> e = tm.values().iterator();
while(e.hasNext()){
methodTemp = e.next();
int mods = methodTemp.getModifiers();
String strm = Modifier.toString(mods); //方法修饰符
System.out.print(" \n"+strm);
System.out.print(" "+methodTemp.getReturnType().getSimpleName()); //返回类型
System.out.print(" "+methodTemp.getName()+"("); //方法名
Class [] p = methodTemp.getParameterTypes(); //打印参数
for(int k=0;k<p.length;k++){

System.out.print(p[k].getSimpleName());
if(p.length>k+1){
System.out.print(",");
}
}
System.out.print(")");
Class []ep = methodTemp.getExceptionTypes(); //打印抛出的异常
if(ep.length!=0){
System.out.print("throws ");
for(int j=0;j<ep.length;j++){
System.out.print(ep[j].getSimpleName());
if(ep.length>j+1)System.out.print(",");
}
}

}
}catch (ClassNotFoundException e){
System.out.println(e.toString());
}
}
//测试
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
String className;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("Please input the name of the class,'quit' to exit:");
className = br.readLine();
if(className.equals("quit")){
System.exit(0);
}
PrintMethods.printAll(className);
}

}

}
loveofmylife 2009-10-09
  • 打赏
  • 举报
回复
import java.lang.reflect.*;
public class ReflectionTest {
public static void main(String[] args) {
Class c=null;
try {
c=Class.forName("java.lang.String");
System.out.println("package "+c.getPackage().getName()+";");
System.out.print(Modifier.toString(c.getModifiers())+" ");
System.out.print("class "+c.getSimpleName()+" ");
if (c.getSuperclass()!=Object.class) {
System.out.print("extends " + c.getSuperclass().getSimpleName());
}
Class[] inters=c.getInterfaces();
if(inters.length>0){
System.out.print("implements ");
for(int i=0;i<inters.length;i++){
System.out.print(inters[i].getSimpleName());
if(i<inters.length-1){
System.out.print(",");
}
}
}
System.out.println("{");
printFields(c);
printMethods(c);
System.out.println("}");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static void printFields(Class c){
Field[] field=c.getDeclaredFields();
if(field.length>0){
for(int i=0;i<field.length;i++){
System.out.println(Modifier.toString(field[i].getModifiers())+" "+field[i].getType().getSimpleName()+" "+field[i].getName()+";");
}
}
}
public static void printMethods(Class c){
Method[] method=c.getDeclaredMethods();
if(method.length>0){
for(int i=0;i<method.length;i++){
Class[] parameter=method[i].getParameterTypes();
System.out.print(Modifier.toString(method[i].getModifiers())+" "+method[i].getReturnType().getSimpleName()+" "+method[i].getName()+"(");
for(int j=0;j<parameter.length;j++){
System.out.print(parameter[j].getSimpleName()+" args");
if(j!=parameter.length-1){
System.out.print(",");
}
}
System.out.print(") ");
Class exception[]=method[i].getExceptionTypes();

if (exception.length>0) {
System.out.print("throws ");
for (int j = 0; j < exception.length; j++) {
System.out.print(exception[j].getSimpleName());
}
}
System.out.println("{");
System.out.println("\t... ...");
System.out.println("}");
}

}
}

}

打印String类结构,可以参考一下。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧