我在第三方设计的设计很差JAR,我需要访问其中一个私有字段.例如,为什么我需要选择私人领域是否有必要?
class IWasDesignedPoorly {
    private Hashtable stuffIWant;
}
IWasDesignedPoorly obj = ...;
我如何使用反射来获得价值stuffIWant?
这是关于java私有构造函数的这个问题的后续内容.
假设我有以下课程:
class Foo<T>
{
    private T arg;
    private Foo(T t) {
        // private!
        this.arg = t;
    }   
    @Override
    public String toString() {
        return "My argument is: " + arg;
    }   
}
我如何构建new Foo("hello")使用反射?
回答
根据jtahlborn的回答,以下作品:
public class Example {
    public static void main(final String[] args) throws Exception {
        Constructor<Foo> constructor;
        constructor = Foo.class.getDeclaredConstructor(Object.class);
        constructor.setAccessible(true);
        Foo<String> foo = constructor.newInstance("arg1");
        System.out.println(foo);
    }   
}
这是本书中的一个问题:https://www.cl.cam.ac.uk/teaching/0506/ConcSys/cs_a-2005.pdf第28页
你能编写一个额外的Java类来创建一个对象,当传递给测试方法时会导致它打印"Here!"吗?正如我在代码中所说,编辑A类本身,或使用反射,序列化或本机方法等库功能被视为作弊!如果没有人能在一周左右发现它,我会在讲座中提供一些提示.博士生都没有得到它.
public class A {
  // Private constructor tries to prevent A
  // from being instantiated outside this
  // class definition
  //
  // Using reflection is cheating :-)
  private A() {
  }
  //  ’test’ method checks whether the caller has
  //  been able to create an instance of the ’A’
  //  class. Can this be done even though the
  //  constructor is private?
  public static void test(Object o) {
    if (o instanceof A) {
      System.out.println("Here!"); …我正在编写一个测试用例,被测JUnit方法采用一个带有私有构造函数作为参数的最终类。由于我无法new使用我尝试使用的关键字实例化它,Mockito但发现Mockito它不喜欢final class. 我去使用PowerMockito这对我来说似乎合理但它PowerMockito.mockStatic(Field.class);是一个无效的方法,我需要一个引用,Field以便我可以在调用该方法时将它作为参数传递。
我想赶上,IllegalArgumentException但首先我需要将引用Field作为参数传递
测试方法
public boolean accept(Field field) { 
    if( ignoreNulls ) {
        try {
            if( field.get( super.getObject() ) == null ) {
                return false;
            }
        } catch (IllegalArgumentException e) {
        } catch (IllegalAccessException e) {
        }
    }
    return super.accept(field); 
} 
JUnit 测试用例
   @Test(expected=IllegalArgumentException.class)
    public void testAccept() throws Exception {
      DefaultToStringBuilder builder = new DefaultToStringBuilder(new Object());
      PowerMockito.mockStatic(Field.class);
      builder.accept(?);
} …java ×4
private ×2
reflection ×2
class ×1
constructor ×1
field ×1
junit ×1
mockito ×1
powermockito ×1