package com.googosoft.demo1.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * author:songyan * date: 2020/4/28 * desc: 反射 **/ public class Test { public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { Class clazz = Student.class; Student student = (Student) test2(clazz); System.out.println(student); } public static Object test2(Class clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constroctor = clazz.getConstructor(String.class, String.class, Integer.class, String.class); return ((Constructor) constroctor).newInstance("id", "name", 18, "sgagga"); } } /** * author:songyan * date: 2020/4/28 **/ class Student { public String id; public String name; public int age; public String fav; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getFav() { return fav; } public void setFav(String fav) { this.fav = fav; } public Student(String id, String name, Integer age, String fav) { this.id = id; this.name = name; this.age = age; this.fav = fav; } @Override public String toString() { return "Studnet{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", age=" + age + ", fav='" + fav + '\'' + '}'; } }
基于反射创建对象并设置属性
猜你喜欢
转载自www.cnblogs.com/excellencesy/p/12796966.html
今日推荐
周排行