一.構造空對象
public class Solution1 {
public static void main(String[] args) throws Exception {
Solution solution = Solution.class.newInstance();
Solution solution1 = solution.getClass().newInstance();
Solution solution2 = solution.getClass().getConstructor().newInstance();
Solution solution3 = solution.getClass().getDeclaredConstructor().newInstance();
Solution solution4 = Solution.class.newInstance();
Solution solution5 = Solution.class.getConstructor().newInstance();
Solution solution6 = Solution.class.getDeclaredConstructor().newInstance();
Solution solution7 = (Solution) Class.forName("Solution").newInstance();
Solution solution8 = (Solution) Class.forName("Solution").getConstructor().newInstance(); // 無參也可用getConstructor()
Solution solution9 = (Solution) Class.forName("Solution").getDeclaredConstructor().newInstance(); // 無參也可用getConstructor()
System.out.println(solution1 instanceof Solution); // true
System.out.println(solution2 instanceof Solution); // true
System.out.println(solution3 instanceof Solution); // true
System.out.println(solution4 instanceof Solution); // true
System.out.println(solution5 instanceof Solution); // true
System.out.println(solution6 instanceof Solution); // true
System.out.println(solution7 instanceof Solution); // true
System.out.println(solution8 instanceof Solution); // true
System.out.println(solution8 instanceof Solution); // true
}
}
補充:new關鍵字和newInstance()方法的區別:
newInstance: 弱類型。低效率。只能調用無參構造。
new: 強類型。相對高效。能調用任何public構造。
JAVA9的API 我們可以反射中的newInstance()方法不推薦使用
推薦使用:clazz.getDeclaredConstructor().newInstance()
二.構造有參對象
public class Solution {
private String str;
private int num;
public Solution() {
}
public Solution(String str, int num) {
this.str = str;
this.num = num;
}
public Solution(String str) {
this.str = str;
}
@Override
public String toString() {
return "Solution [str=" + str + ", num=" + num + "]";
}
public static void main(String[] args) throws Exception {
Class[] classes = new Class[] { String.class, int.class };
Solution solution = Solution.class.getConstructor(classes).newInstance("hello1", 10);
System.out.println(solution);
Solution solution2 = solution.getClass().getDeclaredConstructor(String.class).newInstance("hello2");
System.out.println(solution2);
System.out.println(solution instanceof Solution);// true
System.out.println(solution2 instanceof Solution);// true
}
}
測試結果:
Solution [str=hello1, num=10]
Solution [str=hello2, num=0]
true
true
********* getConstructor()和getDeclaredConstructor()區別:*********
getDeclaredConstructor(Class<?>… parameterTypes)
這個方法會返回制定參數類型的所有構造器,包括public的和非public的,當然也包括private的。
getDeclaredConstructors()的返回結果就沒有參數類型的過濾了。
getConstructor(Class<?>… parameterTypes)
這個方法返回的是上面那個方法返回結果的子集,只返回制定參數類型訪問權限是public的構造器。
getConstructors()的返回結果同樣也沒有參數類型的過濾。