初学反射并复写ToString方法(还未彻底掌握)

package Fanshe;

import java.lang.reflect.*;

//import Fanshe.Student;
class Person{
    public void  run(){
        System.out.println("运动");
    }
}
class Student{
    public int id;
    public String name;

 Student(int id, String name) {
    this.id = id;
    this.name = name;
}

public Student(String name) {
    this.name = name;
}

public Student() {
   id=25;
}
public void fun(String str){
    System.out.println(str);
}
private void print(int a,double b){
    System.out.println(a);
    System.out.println(b);
    }
}
public class Demo1 {
    public static void main(String[] args) throws ClassNotFoundException,
            IllegalAccessException, InstantiationException,
            NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
       /**
        * 得到class对象的三种方法
        * */
        Class c1=Student.class;  //通过类名.class 获取Class对象
//        Student stu=new Student();
//        Class c2=stu.getClass();  //通过对象的getClass方法得到Class对象
        Class c3=Class.forName("Fanshe.Student");  //通过Class中的静态方法forName("类全名")得到Class对象
      /**
       *
       * 关于构造器
       * */

        Student stu=(Student) c1.newInstance();
        System.out.println(stu.id);
        //因为没有class<> 没有指明类型 所有需要向下转型 同时抛出异常IllegalAccessException
        //newInstance() 只能调用无参构造器



        Constructor con=c1.getConstructor();   //调用无参构造器
        Constructor con1=c1.getConstructor(String.class);
        //调用有参构造器 参数是Class<?>... parameterTypes
        //getConstructor 只能得到公有(public)的构造器
        Student stud=(Student) con.newInstance();
        Student stud1=(Student) con1.newInstance("jjjjj");  //传入参数
        System.out.println(stud.id);


        //如何调用不是公有的构造器
//        getDeclaredConstructor 获取任意一个构造器
        Constructor con4=c1.getDeclaredConstructor(int.class,String.class);

        /* 获取所有public构造器 */

        java.lang.reflect.Constructor[] cons3=c1.getConstructors();
        //获取所有构造器
        Constructor[] cons2=c1.getDeclaredConstructors();

        /***
         *
         * -----------------------------------------------
         * 关于成员变量
         * */
        Field field=c1.getField("name");
        // 得到构造器之后 将字段(变量)作为参数传入getField方法中
        field.set(stu,"ght");
        //field对象调用set 为stu对象的name 赋值为ght
        System.out.println(field.get(stu));
        //调用get方法得到这个name值
        /***
         * 注意事项 getField 只能获取public的属性
         * */

        /**
         * _______------------------------
         * getDeclaredField 得到一个属性
         * */

        Field field1=c1.getDeclaredField("id");
        // 得到构造器之后 将字段(变量)作为参数传入getDeclaredField方法中
        field1.setAccessible(true);
        //打开私有权限
        field1.set(stu,64);
        //field1对象调用set 为stu对象的 赋值为64
        System.out.println(field1.get(stu));
        //调用get方法得到这个id值

        Field[] fidldArraypublic=c1.getFields();
        //得到所有的public 属性
        Field[] fidldArrayall=c1.getDeclaredFields();
        //得到所有的 属性


        /***
         *
         * -----------------------------------------------
         * 关于成员方法
         * */
        Method method=c1.getMethod("fun", String.class);
//        getMethod ("方法名",类型.class)
        method.invoke(stu,"您好");
//        getMethod  获取一个公有的方法



        Method method1=c1.getDeclaredMethod("print", int.class, double.class);
//        getDeclaredMethod ("方法名",类型.class)
        method1.setAccessible(true);
        //打开私有权限
        method1.invoke(stu,1,1);
//        getDeclaredMethod  获取一个的方法

        /**
         *
         *关于父类的方法
         *getDeclaredMethod 无法从父类接收到继承的方法 NoSuchMethodException
         * 但是可以通过getMethods 得到public 公共的方法 或者子类去复写这个方法
         * */
//        Method method2=c1.getDeclaredMethod("run");
        getDeclaredMethod ("方法名",类型.class)
//        method1.setAccessible(true);
//        //打开私有权限
//        method1.invoke(stu);

        //获取所有的public的方法 包括父类或者接口的public的方法
         Method[] methodsPublic=c1.getMethods();

        /*获取所有的方法*/ /**不*/  /*包括父类或者接口的public的方法*/
        Method[] methodsall=c1.getDeclaredMethods();
    }
}

复写ToString方法

package com.lhy.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ToString {
	static String s = "";
	static String kong = "";
	static int count = 0;

	public static String toString(Object o) throws Exception {
		Class c = o.getClass();
		//取出Object里面的参数及类型
		Field[] f = c.getDeclaredFields();
		for (int j = 0; j < count; j++) {
			kong += " ";
		}
		for (int i = 0; i < f.length; i++) {
			f[i].setAccessible(true);
			if (f[i].getType().isPrimitive()
					|| f[i].getType().equals(String.class)) {//判断是否是原子型或者是String类型
				s += kong + f[i].getType().getSimpleName() + "  "
						+ f[i].getName() + "=" + f[i].get(o) + "\r\n";
				count = 0;
			} else {
				count = +4;
				if (f[i].get(o) != null && !fun(f[i])) {//判断是否有toString()方法,没有的话运行一下代码
					s += kong + f[i].getType().getSimpleName() + "  "
							+ f[i].getName() + "={\r\n";
					toString(f[i].get(o));
					s +=kong+"}\r\n";
					kong = "";
				} else {//有toString()方法,运行一下代码
					s += kong + f[i].getType().getSimpleName() + "  "
							+ f[i].getName() + "={" + f[i].get(o) + "\r\n";
					toString(f[i].get(o));
					s +=kong+"}\r\n";
					kong = "";
				}count += 2;
			}
         
		}
		return "[\r\n" + s + "]";
	}

	public static boolean fun(Field f) {
        //判断是否有toString()方法,有返回true
		Method[] m = f.getType().getDeclaredMethods();
		for (int i = 0; i < m.length; i++) {
			String[] str = m[i].getDeclaringClass().toString().split(" ");
			if (m[i].toGenericString().equals(
					"public java.lang.String " + str[str.length - 1]
							+ ".toString()"))
				return true;
		}
		return false;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值