JAVA反射实例

本文提供两个Java反射技术的应用实例,包括通过类名获取类的所有构造函数、方法和变量,并演示了如何使用Method对象来调用静态方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

下面是java反射的两个例子

Reflection,通过一个类名,打印出构造函数,方法和变量

  1. package senior; 
  2.  
  3. import java.lang.reflect.Constructor; 
  4. import java.lang.reflect.Field; 
  5. import java.lang.reflect.Method; 
  6. import java.lang.reflect.Modifier; 
  7. import java.util.Scanner; 
  8.  
  9. public class ReflectionTest { 
  10.  
  11.     /**
  12.      * @param args
  13.      */ 
  14.     public static void main(String[] args) { 
  15.         // TODO Auto-generated method stub 
  16.         String name; 
  17.         if (args.length > 0
  18.             name = args[0]; 
  19.         else
  20.             System.out.println("Enter class name (e.g. java.util.Date): "); 
  21.             Scanner in = new Scanner(System.in); 
  22.             name = in.nextLine(); 
  23.         } 
  24.         try
  25.             Class<?> cl = Class.forName(name); 
  26.             Class<?> superClass = cl.getSuperclass(); 
  27.             String modifiers = Modifier.toString(cl.getModifiers()); 
  28.             if (modifiers.length() > 0
  29.                 System.out.print(modifiers + " "); 
  30.             System.out.print("class " + name); 
  31.             if (superClass != null && superClass != Object.class
  32.                 System.out.print("extends " + superClass.getName()); 
  33.             System.out.print("\n{\n"); 
  34.             printConstructors(cl);// 打印构造方法 
  35.             System.out.println(); 
  36.             printMethods(cl);// 打印方法 
  37.             System.out.println(); 
  38.             printFields(cl);// 打印数据成员 
  39.             System.out.println("}"); 
  40.  
  41.         } catch (ClassNotFoundException e) { 
  42.             // TODO Auto-generated catch block 
  43.             e.printStackTrace(); 
  44.         } 
  45.         System.exit(0); 
  46.  
  47.     } 
  48.  
  49.     private static void printFields(Class<?> cl) { 
  50.         // TODO Auto-generated method stub 
  51.         Field[] fields = cl.getDeclaredFields(); 
  52.         for (Field f : fields) { 
  53.             System.out.print("\t"); 
  54.             Class<?> type = f.getType(); 
  55.             String name = f.getName(); 
  56.             String modifiers = Modifier.toString(f.getModifiers()); 
  57.             if (modifiers.length() > 0
  58.                 System.out.print(modifiers + " "); 
  59.             System.out.println(type.getName() + " " + name + ";"); 
  60.         } 
  61.     } 
  62.  
  63.     private static void printMethods(Class<?> cl) { 
  64.         // TODO Auto-generated method stub 
  65.         Method[] methods = cl.getDeclaredMethods(); 
  66.         for (Method m : methods) { 
  67.             System.out.print("\t"); 
  68.             Class<?> retType = m.getReturnType(); 
  69.             String name = m.getName(); 
  70.             String modifiers = Modifier.toString(m.getModifiers()); 
  71.             System.out.print(modifiers + " "); 
  72.             System.out.print(retType + " " + name + "("); 
  73.             @SuppressWarnings("rawtypes"
  74.             Class[] paramTypes = m.getParameterTypes(); 
  75.             for (int j = 0; j < paramTypes.length; j++) { 
  76.                 if (j > 0
  77.                     System.out.print(", "); 
  78.                 System.out.print(paramTypes[j].getName()); 
  79.             } 
  80.             System.out.println(");"); 
  81.         } 
  82.     } 
  83.  
  84.     private static void printConstructors(Class<?> cl) { 
  85.         // TODO Auto-generated method stub 
  86.         @SuppressWarnings("rawtypes"
  87.         Constructor[] constructors = cl.getDeclaredConstructors(); 
  88.         for (Constructor<?> c : constructors) { 
  89.             System.out.print("\t"); 
  90.             String name = c.getName(); 
  91.             String modifiers = Modifier.toString(c.getModifiers()); 
  92.             System.out.print(modifiers + " "); 
  93.             System.out.print(name + "("); 
  94.             @SuppressWarnings("rawtypes"
  95.             Class[] paramTypes = c.getParameterTypes(); 
  96.             for (int j = 0; j < paramTypes.length; j++) { 
  97.                 if (j > 0
  98.                     System.out.print(", "); 
  99.                 System.out.print(paramTypes[j].getName()); 
  100.             } 
  101.             System.out.println(");"); 
  102.         } 
  103.     } 
  104.  
package senior;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;

public class ReflectionTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String name;
		if (args.length > 0)
			name = args[0];
		else {
			System.out.println("Enter class name (e.g. java.util.Date): ");
			Scanner in = new Scanner(System.in);
			name = in.nextLine();
		}
		try {
			Class<?> cl = Class.forName(name);
			Class<?> superClass = cl.getSuperclass();
			String modifiers = Modifier.toString(cl.getModifiers());
			if (modifiers.length() > 0)
				System.out.print(modifiers + " ");
			System.out.print("class " + name);
			if (superClass != null && superClass != Object.class)
				System.out.print("extends " + superClass.getName());
			System.out.print("\n{\n");
			printConstructors(cl);// 打印构造方法
			System.out.println();
			printMethods(cl);// 打印方法
			System.out.println();
			printFields(cl);// 打印数据成员
			System.out.println("}");

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.exit(0);

	}

	private static void printFields(Class<?> cl) {
		// TODO Auto-generated method stub
		Field[] fields = cl.getDeclaredFields();
		for (Field f : fields) {
			System.out.print("\t");
			Class<?> type = f.getType();
			String name = f.getName();
			String modifiers = Modifier.toString(f.getModifiers());
			if (modifiers.length() > 0)
				System.out.print(modifiers + " ");
			System.out.println(type.getName() + " " + name + ";");
		}
	}

	private static void printMethods(Class<?> cl) {
		// TODO Auto-generated method stub
		Method[] methods = cl.getDeclaredMethods();
		for (Method m : methods) {
			System.out.print("\t");
			Class<?> retType = m.getReturnType();
			String name = m.getName();
			String modifiers = Modifier.toString(m.getModifiers());
			System.out.print(modifiers + " ");
			System.out.print(retType + " " + name + "(");
			@SuppressWarnings("rawtypes")
			Class[] paramTypes = m.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

	private static void printConstructors(Class<?> cl) {
		// TODO Auto-generated method stub
		@SuppressWarnings("rawtypes")
		Constructor[] constructors = cl.getDeclaredConstructors();
		for (Constructor<?> c : constructors) {
			System.out.print("\t");
			String name = c.getName();
			String modifiers = Modifier.toString(c.getModifiers());
			System.out.print(modifiers + " ");
			System.out.print(name + "(");
			@SuppressWarnings("rawtypes")
			Class[] paramTypes = c.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

}

运行结果:


MethodPointer相当于C/C++中的回调函数

  1. package senior; 
  2.  
  3. import java.lang.reflect.InvocationTargetException; 
  4. import java.lang.reflect.Method; 
  5.  
  6. public class MethodPointerTest { 
  7.  
  8.     /**
  9.      * @param args
  10.      * @throws NoSuchMethodException
  11.      * @throws SecurityException
  12.      */ 
  13.     public static void main(String[] args) throws SecurityException, 
  14.             NoSuchMethodException { 
  15.         // TODO Auto-generated method stub 
  16.         Method square = MethodPointerTest.class.getMethod("square"
  17.                 double.class); 
  18.         Method sqrt = Math.class.getMethod("sqrt", double.class); 
  19.         printTable(1, 10, 10, square); 
  20.         printTable(1, 10, 10, sqrt); 
  21.     } 
  22.  
  23.     public static double square(double x) { 
  24.         return x * x; 
  25.     } 
  26.  
  27.     private static void printTable(int i, int j, int k, Method f) { 
  28.         // TODO Auto-generated method stub 
  29.         double x = (j - i) / (k - 1); 
  30.         for (double l = i; l <= j; l += x) { 
  31.             double y; 
  32.             try
  33.                 y = (Double) f.invoke(null, l); 
  34.                 System.out.printf("%10.4f|%10.4f%n", l, y); 
  35.             } catch (IllegalArgumentException e) { 
  36.                 // TODO Auto-generated catch block 
  37.                 e.printStackTrace(); 
  38.             } catch (IllegalAccessException e) { 
  39.                 // TODO Auto-generated catch block 
  40.                 e.printStackTrace(); 
  41.             } catch (InvocationTargetException e) { 
  42.                 // TODO Auto-generated catch block 
  43.                 e.printStackTrace(); 
  44.             } 
  45.  
  46.         } 
  47.     } 
  48.  
package senior;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodPointerTest {

	/**
	 * @param args
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 */
	public static void main(String[] args) throws SecurityException,
			NoSuchMethodException {
		// TODO Auto-generated method stub
		Method square = MethodPointerTest.class.getMethod("square",
				double.class);
		Method sqrt = Math.class.getMethod("sqrt", double.class);
		printTable(1, 10, 10, square);
		printTable(1, 10, 10, sqrt);
	}

	public static double square(double x) {
		return x * x;
	}

	private static void printTable(int i, int j, int k, Method f) {
		// TODO Auto-generated method stub
		double x = (j - i) / (k - 1);
		for (double l = i; l <= j; l += x) {
			double y;
			try {
				y = (Double) f.invoke(null, l);
				System.out.printf("%10.4f|%10.4f%n", l, y);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}

运行结果:


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值