求帮助。求帮助

yetinut520 2012-12-10 10:58:15
接收一串字符串,格式像这样的(key=value|key=value||||)key 代表Field的name,value代表set进Object中的值,将他装换成一个Object对象,调用setter方法为其赋值,我用下面的方法调用method.invoke(obj, obj..);测试的时候用的其中一个Bean类Student。Student里面有很多Filed,怎么把value(String)转换invoke方法的第2个参数的类型啊,是像我下面那样一个一个判断吗,还是有别的方法啊。大家帮帮忙=。= 谢谢……^^


package com.ytbysj.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Map.Entry;

import com.ytbysj.beans.Student;
import com.ytbysj.exception.FooException;

/**
* Message Handler类
* @author haniyaseyo
*
*/
public class MessageHandler {

/**
* 将message转换成Map对象
* @param message like:key=value|key=value||||
* @return 通过message转换成的MAP key=value
*/
public static Map<String,String> messageHandler(String message){
//如果message=null则抛出异常
if(message == null) throw new FooException("MessageHandler messageHandler(String message) message=null");
//简单判断message的格式
if(message.indexOf("|") == -1) throw new FooException("MessageHandler messageHandler(String message) message do not contains \"|\"");
if(message.indexOf("=") == -1) throw new FooException("MessageHandler messageHandler(String message) message do not contains \"=\"");

//定义Map对象
Map<String, String> map = new HashMap<String, String>();

//定义StringTokenizer对象 并指定"|"为分隔符
StringTokenizer stken = new StringTokenizer(message, "|");

/*
* 循环StringTokenizer中的对象 并复制到Map中
*/
while (stken.hasMoreTokens()) {
String[] temp = stken.nextToken().split("=");
map.put(temp[0], temp[1]);
}
return map;
}

/**
* 根据给定的message和Class构造一个?对象
* @param message like:key=value|key=value||||||
* @param clazz ?的Class对象
* @return clazz.newInstance()
*/
public static Object getObject(String message, Class<?> clazz){
//获取Map
Map<String, String> map = messageHandler(message);
//判断Map是否为空
if(map.isEmpty()) throw new FooException("MessageHandler getObject(String message, Class<?> clazz) map is empty");

Object obj = null;
try {
obj = clazz.newInstance();
Iterator<Entry<String,String>> ite = map.entrySet().iterator();
while(ite.hasNext()){
Entry<String,String> entry = ite.next();
//取出每一个key value
String item_name = entry.getKey().trim();
String value = entry.getValue().trim();
//构造方法名
String methodName = "set" + String.valueOf(item_name.charAt(0)).toUpperCase() + item_name.substring(1);
//获取Field的类型
Class<?> type = clazz.getDeclaredField(item_name).getType();
System.out.println(methodName + "," + value + "," +type.getName());
//获取Method对象
Method method = clazz.getDeclaredMethod(methodName, type);

//判断Field类型
if(type == value.getClass()){
method.invoke(obj, value);
}else if(type == int.class){
method.invoke(obj, Integer.parseInt(value));
}//..如果在这里接着判断有很多不方便的地方-。-
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return obj;
}

public static void main(String[] args) {
String message = "student_no=0810024103|password= |username=叶婷|sex=男" +
"|moblie=12296736137|native_place=重庆|college= |tie=软件工程|stuclass=09级2班|limits=3";
System.out.println(getObject(message,Student.class));
}
}
...全文
89 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
yetinut520 2012-12-10
  • 打赏
  • 举报
回复
引用 1 楼 Inhibitory 的回复:
可以参考这一段代码的实现 Java code?12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import java.util.LinkedList;import jav……
您好,谢谢你的帮助,我又学到了很多东西,我就把你的加到我的代码里面^^ while (matcher.find()) { Student s = new Student(); s.setKey(matcher.group(1)); s.setValue(matcher.group(2)); students.add(s); } 在Student里面他的属性不全是String类型的。还有就是还有一些的其他的bean类,比如User等,public static Object getObject(String message, Class<?> clazz)所以我定义了一个这样的方法,有没有在获取filed的类型之后将一个字符串转换成这个filed对应的类型的方法啊=。=。
yetinut520 2012-12-10
  • 打赏
  • 举报
回复
您好,谢谢你的帮助,我又学到了很多东西,我就把你的加到我的代码里面^^ while (matcher.find()) { Student s = new Student(); s.setKey(matcher.group(1)); s.setValue(matcher.group(2)); students.add(s); } 在Student里面他的属性不全是String类型的。还有就是还有一些的其他的bean类,比如User等,public static Object getObject(String message, Class<?> clazz)所以我定义了一个这样的方法,有没有在获取filed的类型之后将一个字符串转换成这个filed对应的类型的方法啊=。=。
Inhibitory 2012-12-10
  • 打赏
  • 举报
回复
输出
[Student{key='key1', value='value1'}, Student{key='key2', value='value2'}, Student{key='key3', value='value3'}]
Exception in thread "main" java.lang.Exception: Malformed input
	at com.tur.demo.Hello.grabStudents(Hello.java:25)
	at com.tur.demo.Hello.main(Hello.java:15)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Inhibitory 2012-12-10
  • 打赏
  • 举报
回复
可以参考这一段代码的实现
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Hello {
    public static void main(String[] args) throws Exception {
        // (key=value|key=value|key=value||||)
        String input = "(key1=value1|key2=value2|key3=value3)";
        List<Student> students = grabStudents(input);
        System.out.println(students);

        System.out.println(grabStudents("(key=value|key=value|key=value||||)"));
    }

    public static boolean validateInput(String input) {
        return input.matches("\\(\\w+=\\w+(\\|\\w+=\\w+)*\\)");
    }

    public static List<Student> grabStudents(String input) throws Exception {
        // 验证输入的字符串是否合法
        if (!validateInput(input)) {
            throw new Exception("Malformed input");
        }

        List<Student> students = new LinkedList<Student>();

        String regex = "(\\w+)=(\\w+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            Student s = new Student();
            s.setKey(matcher.group(1));
            s.setValue(matcher.group(2));
            students.add(s);
        }

        return students;
    }
}

class Student {
    String key;
    String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Student{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}';
    }
}

62,614

社区成员

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

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