如何从main()方法访问静态内部类中私有类的私有方法
Solution to Access Private Inner Class Method via Reflection
Alright, let's tackle this problem head-on. Since both the StarLord private inner class (inside Avengers) and its getGamora() method are marked as private, standard Java syntax won't let us access them directly. We need to use reflection to bypass these access modifiers. Here's a working implementation:
Full Working Code
import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class Thanos { public static void main(String[] args) throws Exception { // 1. Instantiate the static inner class Avengers Avengers avngrs = new Thanos.Avengers(); // 2. Retrieve the private inner class StarLord from Avengers Class<?> starLordClass = Avengers.class.getDeclaredClass("Thanos.Avengers.StarLord"); // 3. Get the constructor of StarLord (requires an Avengers instance for non-static inner class) Constructor<?> starLordConstructor = starLordClass.getDeclaredConstructor(Avengers.class); starLordConstructor.setAccessible(true); // Allow access to private constructor Object starLordInstance = starLordConstructor.newInstance(avngrs); // 4. Fetch the private getGamora() method Method getGamoraMethod = starLordClass.getDeclaredMethod("getGamora"); getGamoraMethod.setAccessible(true); // Allow access to private method // 5. Invoke the method to print the desired output getGamoraMethod.invoke(starLordInstance); } static class Avengers { private class StarLord { private void getGamora() { System.out.println("Access me to get a soul for a soul."); } } } }
Breakdown of Key Steps
- Step 1: We start by creating an instance of
Avengers(the static inner class). SinceAvengersis static, we don't need aThanosinstance to instantiate it. - Step 2: Using
getDeclaredClass(), we access the privateStarLordinner class. This method lets us retrieve classes that aren't publicly visible, unlikegetClasses()which only returns public inner classes. - Step 3: Non-static inner classes (like
StarLord) have an implicit constructor parameter that takes their outer class instance (Avengers). We fetch this constructor, enable access to it withsetAccessible(true), then create aStarLordinstance by passing ourAvengersobject. - Step 4: We get the private
getGamora()method usinggetDeclaredMethod(), then callsetAccessible(true)to override the private access restriction. - Step 5: Finally, we invoke the method on our
StarLordinstance, which outputs the required message.
Note on Reflection
Reflection is a powerful tool, but it should be used sparingly. It bypasses Java's built-in access control and can make code harder to maintain, debug, and secure. Use it only when you have no other alternative (like in this specific scenario).
内容的提问来源于stack exchange,提问作者kapishreshth
相关产品推荐
相关产品推荐

