关于反射的一个问题。

philo_xu 2008-01-28 09:15:57
import java.lang.reflect.*;


class ClassTest
{

/**
* @param args
*/
public static void main(String[] args)
{

if(args.length!=1)
{
return;
}
try
{
Class c = Class.forName(args[0]);
Constructor[] cons = c.getDeclaredConstructors();
Class[] params = cons[0].getParameterTypes();
Object[] paramsValue = new Object[params.length];
for(int i=0;i<params.length;i++)
{
if(params[i].isPrimitive())
{
paramsValue[i] = new Integer(i+3);
}
}
Object o = cons[0].newInstance(paramsValue);
Method[] ms = c.getDeclaredMethods();
ms[0].invoke(o, null);
}
catch(Exception e)
{
e.printStackTrace();
}
}


}

class Point
{
int x;
int y;
static
{
System.out.println("Loading Point");
}
void output()
{
System.out.println("x ="+x+", y ="+y);
}
Point(int x,int y)
{
this.x = x;
this.y = y;
}
}

class Line
{
static
{
System.out.println("Loading Line");
}
}


这个反射程序我看的迷迷糊糊,请教高手帮助讲解一下。
尤其是

Object[] paramsValue = new Object[params.length];
for(int i=0;i<params.length;i++)
{
if(params[i].isPrimitive())
{
paramsValue[i] = new Integer(i+3);
}
}
Object o = cons[0].newInstance(paramsValue);
Method[] ms = c.getDeclaredMethods();
ms[0].invoke(o, null);



这一段。把我转晕了。非常头疼。
...全文
97 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuanqingfei 2008-01-29
  • 打赏
  • 举报
回复
好像就是得到一个对象并执行其方法(当然先传递给其整型参数),没有什么特别的吧。

goodmrning 2008-01-28
  • 打赏
  • 举报
回复
学习中
happy_zwc4 2008-01-28
  • 打赏
  • 举报
回复
import java.lang.reflect.*;


class ClassTest
{

/**
* @param args
*/
public static void main(String[] args)
{

if(args.length!=1)
{
return;
}
try
{
Class c = Class.forName(args[0]);//反射得到类
Constructor[] cons = c.getDeclaredConstructors();//取出类里面的构造方法
Class[] params = cons[0].getParameterTypes();//取出构造方法里面的参数类形
Object[] paramsValue = new Object[params.length];//根据参数的个数new Object
for(int i=0;i<params.length;i++)
{
if(params[i].isPrimitive())//如果参数为基本类型的话就执行
{
paramsValue[i] = new Integer(i+3);
}
}
Object o = cons[0].newInstance(paramsValue);//构造器构造一个对象o
Method[] ms = c.getDeclaredMethods();//得到类里面的所有public方法
ms[0].invoke(o, null);//方法ms执行(方法执行一定要由对象执行,除非为static才能由类执行,第二个null是为这个方法提供参数)
}
catch(Exception e)
{
e.printStackTrace();
}
}


}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧