码迷,mamicode.com
首页 > 编程语言 > 详细

反射-Construct-Java

时间:2019-09-29 22:15:29      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:creat   style   div   instant   str   illegal   auth   foreign   time   

 1 import net.dsmxx.PersonFk;
 2 
 3 import java.lang.reflect.Constructor;
 4 import java.lang.reflect.InvocationTargetException;
 5 
 6 /**
 7  * Created with IDEA
 8  * author:foreign
 9  * Date:2019/9/29
10  * Time:20:02
11  */
12 public class ReflectionFk {
13     public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
14         Class clazz = PersonFk.class;
15         //1 获取public的构造方法
16         Constructor[] constructors = clazz.getConstructors();
17         for (Constructor constructor : constructors) {
18             System.out.println("public的构造方法:" + constructor);
19         }
20         //2 根据参数获取构造方法
21         Constructor constructor = clazz.getConstructor(new Class[]{String.class, Integer.class, Boolean.class});
22         System.out.println("String类型的构造方法:" + constructor);
23         //3 构造方法参数
24         Class[] parameterTypes = constructor.getParameterTypes();
25         for (Class para : parameterTypes) {
26             System.out.println("构造方法参数:" + para);
27         }
28         //利用构造方法对象实例化一个类
29         Constructor constructor1 = clazz.getConstructor(new Class[]{String.class, Integer.class, Boolean.class});
30         Object o = constructor1.newInstance("foreign", 27, true);
31         System.out.println("对象:" + o);
32         PersonFk personFk = (PersonFk) o;
33         System.out.println("对象name:" + personFk.getName());
34         System.out.println("对象name:" + personFk.getAge());
35         System.out.println("对象name:" + personFk.getGender());
36     }
37 }

 

反射-Construct-Java

标签:creat   style   div   instant   str   illegal   auth   foreign   time   

原文地址:https://www.cnblogs.com/fangke/p/11609974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!