Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách khởi tạo static inner class bằng reflection trong Java?

Static inner class có thể khởi tạo không cần instance của outer class. Thông thường inner class là một phần của nested class, gọi là Non-static nested classes. Các loại inner class: member inner class, anonymous inner class, local inner class.

Khởi tạo static inner class bằng reflection dùng InnerClass.class.newInstance(). Nếu cần instance của outer class để khởi tạo non-static inner class, chỉ định nó trước toán tử new.

Ví dụ

import java.lang.reflect.*; 

public class InnerclassWithReflectionTest { 
    public static void main(String args[]) { 
        try { 
            InnerClass inner = (InnerClass) InnerClass.class.newInstance(); 
            inner.test(); 
        } catch(Exception e) { 
            e.printStackTrace(); 
        } 
    } 
    // inner class 
    static class InnerClass { 
        public void test() { 
            System.out.println("Welcome to TutorialsPoint !!!"); 
        } 
    } 
}

Kết quả

Welcome to TutorialsPoint !!!