簡體   English   中英

如何反映私有靜態嵌套子類?

[英]How do I reflect a private static nested subclass?

首先,我正在 Kotlin 中尋找答案,但我正在與 Java 庫進行交互。

我需要從一個私有靜態嵌套類中獲取一個實例,該類派生自周圍超類的一個實例。

鑒於您有這些(簡化的)嵌套 Java 類

public abstract class GLFWKeyCallback extends Callback implements GLFWKeyCallbackI {

  public static GLFWKeyCallback create(GLFWKeyCallbackI instance) {
    new Container(instance.address(), instance);
  }

  private static final class Container extends GLFWKeyCallback {

    private final GLFWKeyCallbackI delegate;

    Container(long functionPointer, GLFWKeyCallbackI delegate) {
      super(functionPointer);
      this.delegate = delegate;
    }
  }
}

我通過另一種外部方法將 Container 實例作為 GLFWKeyCallback 取回。 您可以將此方法視為:

public static GLFWKeyCallback getCallback() {
  return GLFWKeyCallback.create(anInternalInstance)
}

在科特林:

val callback:GLFWKeyCallback = getCallback()

// I would now want to cast,
// or in other ways use callback
// as the GLFWKeyCallback.Container class it actually is.

val callbackAsContainer = callback as GLFWKeyCallback.Container // Error: Container is private

val ContainerClass = GLFWKeyCallback::class.nestedClasses.find { it.simpleName?.contains("Container") ?: false }!!
// Gives me a KClass<*> that I don't know how to use, can't find documentation for this kind of circumstance

// If using the class instance itself is not possible I would at least want to get the
// Container.delegate of GLFWKeyCallbackI

val delegateField = ContainerClass.memberProperties.findLast { it.name == "delegate" }!!
val fieldValue = field.get(callback)
// Error: Out-projected type 'KProperty1<out Any, Any?>' prohibits the use of 'public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1'

為什么你不想使用 Java 反射? 您也可以在 Kotlin 中使用它:

val callback = getCallback()
val field = callback::class.java.getDeclaredField("delegate")
field.isAccessible = true
val delegate = field.get(callback) as GLFWKeyCallbackI

您仍然可以通過.getClass()獲取課程。 此示例打印“5”:

public class Example {
    public static void main(String[] args) throws Exception {
        Object o = Target.get();
        Field f = o.getClass().getDeclaredField("field");
        f.setAccessible(true);
        Integer i = (Integer) f.get(o);
        System.out.println(i);
    }
}

public class Target {
    public static Object get() { return new Inner(); }
    private static class Inner {
        private int field = 5;
    }
}

如果您知道確切的名稱:

Class<?> c = Class.forName("com.foo.pkgof.Target$Inner");
c.getDeclaredField("field");

作品。 注意美元。 這是在“外部”和“內部”之間使用的分隔符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM