java-反射-设置属性值

1.概要

1.1.如果用字符型的数据给数值型的数据赋值

1.2.无法用type.valueof(?)赋值

1.3.无法用反射的构造函数统一赋值

1.4.用类型判定去逐个的做数据转换似乎有很麻烦

2.代码 

package test;

import java.lang.reflect.Field;
import java.lang.reflect.Constructor;

public class FanseSetObject {
    public static void main(String[] args) {
	// TODO Auto-generated method stub
	FanseSetObject fanseSetObject = new FanseSetObject();
	fanseSetObject.main();
	//fanseSetObject.maain2();
	//fanseSetObject.main3();
	//fanseSetObject.main4();
	//fanseSetObject.mian5();
    }
    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.getClass().getTypeName());
	    System.out.println(f.getType());
	    try{
		//Object oint = f.getClass()
		String s = "1";
		//Object obj2 = f.getType().getConstructors()[1].newInstance("1");
		//f.set(a, Integer.valueOf("1"));
		//f.set(a, obj2);
	    }catch(Exception e){
		System.out.println(e.toString());
	    }
	    
	}
    }
    public void maain2(){
	Constructor cons[] = Integer.class.getConstructors();
	for(Constructor con:cons){
	    System.out.println(con.getName());
	    Class contypes[] = con.getParameterTypes();
	    for(Class cy:contypes){
		System.out.println("   "+cy.getName());
	    }
	}
    }
    public void mian5(){
	Constructor cons[] = String.class.getConstructors();
	for(Constructor con:cons){
	    System.out.println(con.getName().toString());
	    Class contypes[] = con.getParameterTypes();
	    for(Class cy:contypes){
		System.out.println("   "+cy.getName());
	    }
	}
    }
    public void main3(){
	Integer a = new Integer("1");
	System.out.println(a);
    }
    public void main4(){
	int a = 5;
	System.out.println(int.class.toString());
	Integer b = new Integer("1");
	System.out.println(int.class);
	System.out.println(b.getClass());
	System.out.println(Integer.class);
    }
    class A {
	public String a;
	public Integer b;
    }
}

运行结果

a
java.lang.reflect.Field
class java.lang.String
b
java.lang.reflect.Field
class java.lang.Integer

 

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