先考虑它是否可以单独到一个类,再考虑使用反射

class Stranger {

    public Stranger(final String name) {
        this.name = name;
    }

    private final String greet(final String hello) {
        return hello + name;
    }

    private String name = "";
}

public class PrivateTest {

    public static void main(String args[]) throws Exception {

        Stranger testObj = new Stranger("Walter");
        Class testClass = testObj.getClass();
        // get private property
        Field field = testClass.getDeclaredField("name");
        // Make the field accessible
        field.setAccessible(true);
        
        // get private method
        Class[] typeParams = new Class[] { String.class };
        Method method = testClass.getDeclaredMethod("greet", typeParams);
        // Make the method accessible
        method.setAccessible(true);
        // execute the method
        Object objParams[] = { "hello, " };
        String greet = (String)method.invoke(testObj, objParams);
        
        System.out.println(greet);
    }
}

相关文章:

  • 2022-02-27
  • 2021-09-03
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
猜你喜欢
  • 2022-01-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-09
相关资源
相似解决方案