求一个利用java反射的例子 不太理解反射的作用 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 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类结构,可以参考一下。 我也贴个,以前写的一个小作业,利用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); } }} 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; } } 关于对象数组的问题。。 JMF的processor 问题 java 如何将 int[] 写入文件?? snmp读取交换机有多少设备在线 查询时做到类似于word的效果 文件上传 String问题,关于charset 如何让JAVA Application 程序缩在WINDOWS任务栏上 在我的电脑上能编译出class文件 ,不知道什么原因不能运行,菜鸟问题,见笑! 【求助】 redis 实时并列排行榜解决方案 新人求教:单机项目转C/S的疑惑 请问各位;java在程序中如何查看本机的进程ID
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类结构,可以参考一下。
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);
} }}
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;
}
}