黑马程序员技术交流社区

标题: 反射课程中 糊涂了~~ 秋香姐!! [打印本页]

作者: 郭宁    时间: 2012-5-17 16:49
标题: 反射课程中 糊涂了~~ 秋香姐!!
Constructor[] con=Class.forName("java.lang.String").getConstructors();

这里 为何不能用 con.length  ??? 难道不是数组么???
作者: 李哲    时间: 2012-5-17 16:54
  1. public class RuntimeDemo {

  2.        
  3.         public static void main(String[] args) throws  Exception {

  4.                 Constructor[] con=Class.forName("java.lang.String").getConstructors();
  5.                 System.out.println(con.length);

  6.         }

  7. }
复制代码
可以使用。
作者: 郭宁    时间: 2012-5-17 16:58
李哲 发表于 2012-5-17 16:54
可以使用。
  1.         public static void main(String[] args)
  2.         {
  3.                 try {
  4.                         int[] i = new int[2];
  5.                         Constructor[] con=Class.forName("java.lang.String").getConstructors();
  6.                 } catch (SecurityException e) {
  7.                         // TODO Auto-generated catch block
  8.                         e.printStackTrace();
  9.                 } catch (ClassNotFoundException e) {
  10.                         // TODO Auto-generated catch block
  11.                         e.printStackTrace();
  12.                 }
  13.                 System.out.println(con.length);
  14.         }
复制代码
我是这样写的不能用,研究了一下 问题处在 try~~~  try成局部变量了????
作者: 郭振    时间: 2012-5-17 17:02
首先,它肯定是数组。.length  是可以用的。它的返回值类型是int型。
String a1="abc";               
Constructor[] con=Class.forName("java.lang.String").getConstructors();       
         int x=con.length;//这样写就可以通过了。要用int型变量记录它
     System.out.println(x);


作者: 袁冬梅    时间: 2012-5-17 17:03
郭宁 发表于 2012-5-17 16:58
我是这样写的不能用,研究了一下 问题处在 try~~~  try成局部变量了???? ...

对的,你的con要么在try外面先申明变量,要么你就把那个syso放到try块里面
作者: 李哲    时间: 2012-5-17 17:04
con定义在try的大括号内,只在大括号内有效。外面突然出来一个con,自然会报错。
把Constructor[] con定义在外面就可以。这是异常的知识,我也在看。前面的知识。
  1. public static void main(String[] args)
  2.     {
  3.                          Constructor[] con=null;
  4.             try {
  5.                     int[] i = new int[2];
  6.                     con=Class.forName("java.lang.String").getConstructors();
  7.             } catch (SecurityException e) {
  8.                     // TODO Auto-generated catch block
  9.                     e.printStackTrace();
  10.             } catch (ClassNotFoundException e) {
  11.                     // TODO Auto-generated catch block
  12.                     e.printStackTrace();
  13.             }
  14.             System.out.println(con.length);
  15.     }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2