java-反射-属性赋值-字符类型转数值类型-用构造函数实现

1.概述

1.1 用构造函数设置属性值

1.代码 

package test;

import java.lang.reflect.Field;
public class ReflectSetFieldForSimpleType {

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	ReflectSetFieldForSimpleType rs = new ReflectSetFieldForSimpleType();
	rs.main();
    }

    public void main() {
	A a = new A();
	Field[] field = a.getClass().getFields();
	for (Field f : field) {
	    System.out.println(f.getName());
	    // System.out.println(f.getType().getTypeName());
	    // System.out.println(f.getType().getSimpleName());
	    try {
		Object o = "1";
		if (!f.getType().getSimpleName().equals("String") && !f.getType().getSimpleName().equals("string")) {
		    Object obj2 = f.getType().getConstructors()[1].newInstance(o);
		    f.set(a, obj2);
		} else {
		    f.set(a, o);
		}
	    } catch (Exception e) {
		System.out.println(e.toString());
	    }
	}
    }

    class A {
	public Integer a;
	public Long b;
	public String c;
    }
}

3.运行效果

a
b
c

 

你可能感兴趣的:(java-编码笔记)