簡體   English   中英

如何在不使用靜態上下文的類名的情況下訪問Java中的.class對象

[英]How to access the .class object in java without using the class name from a static context

在Java中,可以在不使用(即鍵入)類名的情況下訪問該類。 一個例子

public class Example {

    /**
     * Non static context, can only be called from an instance.
     */
    public void accessClass() {
        System.out.println(this.getClass());
    }

}

但是,在靜態上下文中,沒有類似的方法,只有.class靜態字段。 這個問題的重點是從Java類本身而不是從其他類訪問.class。

public class Example2 {
    //field used to demonstrate what is meant by "indirectly referencing the class name.
    private static Class<Example2> otherClass = Example2.class;
    private static int intField = 1;
   /**
     * Non static context, can only be called from an instance.
     */
     public static void accessClass() {

        // The .class static field can be accessed by using the name of the class
        System.out.println(Example2.class);

        // However the following is wrong
        // System.out.println(class);

        // Accessing static fields is in general possible
        System.out.println(intField);

        // Accessing a static field of the same Class is also possible, but does not satisfy the answer since the class name has been written in the declaration of the field and thus indirectly referenced.
        System.out.println(otherClass);

    }

}

有沒有一種方法可以從同一個類的靜態上下文中訪問一個類的.class對象,而無需引用該類名(無論是直接還是間接)?

另一個限制是不允許答案實例化該類或使用.getClass()實例方法。

我在上面創建了一些示例,試圖證明我的發現。 我很驚訝地注意到,如果沒有在同一個類中鍵入類名,我將找不到一種訪問.class字段的方法。

這僅僅是某些設計決策的副作用嗎?或者是否有根本原因導致沒有類名就無法訪問.class

我發現的一種方法是首先獲取當前堆棧跟蹤:

StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement current = stackTrace[1];

然后,調用getClassName並將其傳遞給Class.forName

Class<?> clazz = Class.forName(current.getClassName());

使用StackWalker API的Java 9方法

Class<?> currentClass = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE)
        .walk(s -> s.map(StackFrame::getDeclaringClass).findFirst().orElseThrow());

這種方法避免完全使用類名。


至於為什么whis不是核心語言功能的原因,我只能猜測,但是我想到的一件事是嵌套類的一些復雜性,這些復雜性會使通過某些關鍵字實現此功能變得復雜。 如果沒有一種方法可以從嵌套類中引用多個外部類,則添加它沒有多大意義。

另一個原因是,這並不是非常有用-這不是我從未錯過的功能。 使用當今的IDE及其強大的重構工具,即使以后重命名了類,使用類名也不會造成太大問題。 即使在生成源代碼時,替換類名也相對簡單。

暫無
暫無

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

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