本帖最后由 chslzj 于 2013-7-6 11:46 编辑
toString方法没有参数,只有调用对象 我这样得到方法 Method toStringMethod=Class.forName(className).getMethod("toString");
当这样调用方法时,却没有输出
toStringMethod.invoke(point1);
下面是整个的源码里面的className是ReflectPoint,程序结果是:
2
3
1
2- /**
- *
- */
- package com.itheima.test;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.util.Properties;
- /**
- * @author Administrator
- *
- */
- public class ReflectTest{
- public static void main(String[] args) throws Exception {
- InputStream ips=new FileInputStream("config.properties");//从文件中读取类名
- Properties pro=new Properties();
- pro.load(ips);
- ips.close();
- String className=pro.getProperty("className");
- //得到构造方法
- Constructor constructor=Class.forName(className).getConstructor(int.class,int.class);
- //使用构造方法得到对象
- ReflectPoint point1=(ReflectPoint)constructor.newInstance(1,2);
- ReflectPoint point2=(ReflectPoint)constructor.newInstance(2,3);
- //得到类中成员变量x对于的类
- Field fieldY=Class.forName(className).getField("y");
- //输出对象point1,point2对应的y的值
- System.out.println(fieldY.get(point1));
- System.out.println(fieldY.get(point2));
- //得到类中成员变量x对于的类
- //Field fieldX=Class.forName(className).getField("x");
- //对于private的变量不能直接用getField来得到成员变量,应该使用getDeclaredField
- Field fieldX=Class.forName(className).getDeclaredField("x");
- //输出对象point1,point2对应的x的值
- //因为x还是private,不能直接读取,要设置权限
- fieldX.setAccessible(true);
- System.out.println(fieldX.get(point1));
- System.out.println(fieldX.get(point2));
- //下面更改point1中String类型的值,长度如果大于4,就截断
- Field[] fields=Class.forName(className).getFields();
- //这里先把toString方法用反射的方式得到
- Method toStringMethod=Class.forName(className).getMethod("toString");
- toStringMethod.invoke(point1);
-
- for(Field field:fields)
- if(field.getType()==String.class)//字节码用==判断
- {
- String oldValue=(String)field.get(point1);
- String newValue=oldValue.substring(0, 4);
- field.set(point1, newValue);
- }
- toStringMethod.invoke(point1);
-
- }
- }
- class ReflectPoint {
- private int x;
- public int y;
- public String str1 = "football";
- public String str2 = "basketball";
- public String str3 = "itcast";
-
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return str1+":"+str2+":"+str3;
- }
- }
复制代码 |