Java反射机制剖析:功能以及举例

发表于:2012-2-10 09:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:lfsf802    来源:51Testing软件测试网采编

分享:

  示例代码:

  1. import java.lang.reflect.Constructor;  
  2. public class TestConstructor {  
  3.     /**  
  4.      * @param args  
  5.      * @throws ClassNotFoundException   
  6.      * @throws SecurityException   
  7.      * @throws NoSuchMethodException   
  8.      */ 
  9.     public static void main(String[] args) throws Exception {  
  10.         // TODO Auto-generated method stub  
  11.         Class classType=Class.forName(args[0]);  
  12.         Constructor Constructor= classType.getConstructor();  
  13.           
  14.             System.out.println(Constructor.toString());  
  15.           
  16.     }  
  17. }

  5)新建类的实例

  调用类的Class对象的newInstance方法

  1. import java.lang.reflect.Constructor;  
  2.  
  3.  
  4. public class TestConstructor {  
  5.     /**  
  6.      * @param args  
  7.      * @throws ClassNotFoundException   
  8.      * @throws SecurityException   
  9.      * @throws NoSuchMethodException   
  10.      */ 
  11.     public static void main(String[] args) throws Exception {  
  12.         // TODO Auto-generated method stub  
  13.         Class classType=Class.forName(args[0]);  
  14.         //Constructor Constructor= classType.getConstructor();  
  15.         Object inst=classType.newInstance();  
  16.         System.out.println(inst);     
  17.     }  
  18. }

  调用默认Constructor对象的newInstance方法

  1. import java.lang.reflect.Constructor;  
  2.  
  3.  
  4. public class TestConstructor {  
  5.     /**  
  6.      * @param args  
  7.      * @throws ClassNotFoundException   
  8.      * @throws SecurityException   
  9.      * @throws NoSuchMethodException   
  10.      */ 
  11.     public static void main(String[] args) throws Exception {  
  12.         // TODO Auto-generated method stub  
  13.         Class classType=Class.forName(args[0]);  
  14.         Constructor Constructor= classType.getConstructor();  
  15.         Object inst=Constructor.newInstance();  
  16.         System.out.println(inst);     
  17.     }  
  18. }

  调用带参数Constructor对象的newInstance方法

  1. Class classType=User.class 
  2. Constructor constructor2 =  
  3.         classType.getDeclaredConstructor(int.class, String.class);  
  4.  
  5. Object inst = constructor2.newInstance(1"123");  
  6.  
  7. System.out.println(inst);

相关链接:

Java反射机制剖析:定义和API

22/2<12
100家互联网大公司java笔试题汇总,填问卷领取~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号