1 package com.dy.xidian; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 6 class A { 7 private void a() { 8 System.out.println("This is a function"); 9 } 10 } 11 public class TestReflect { 12 public static void main(String[] args) throws NoSuchMethodException, 13 SecurityException, IllegalAccessException, 14 IllegalArgumentException, InvocationTargetException { 15 A a = new A(); 16 Method g = a.getClass().getDeclaredMethod("a"); 17 g.setAccessible(true); 18 g.invoke(a); 19 } 20 }
通过反射机制可以访问A中的私有方法。
时间: 2024-10-08 23:13:57