Java反射 - getDeclaredConstructor().newInstance()得到實例化對象


Java反射 - getDeclaredConstructor().newInstance()得到實例化對象

  • class.newInstance()實例化只能直接調用構造參數
  • class.getDeclaredConstructor().newInstance()實例化可以調用靜態類和構造參數

實現類

public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    UserService.class.getDeclaredConstructor().newInstance();
    System.out.println("=====================");
    UserService.class.newInstance();
}

class對象代碼

public class UserService {

    static {
        System.out.println("static");
    }
    
    public UserService() {
        System.out.println("test");
    }
}

得到的結果

202111291240338


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM