Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从HashMap构造一个类_Java_Android_Hashmap - Fatal编程技术网

Java 从HashMap构造一个类

Java 从HashMap构造一个类,java,android,hashmap,Java,Android,Hashmap,我想编写一个构造函数来设置HashMap中的值。你能告诉我最好的方法是什么吗 我现在使用switch语句调用基于HashMap键的方法,但我想知道是否有更好的替代方法 仅供参考,在myItems类中,我实际上有25个变量要设置 public class MainClass{ BufferedReader br = new BufferedReader(new FileReader(file)); String[] datakey = br.readLine().split(";"

我想编写一个构造函数来设置HashMap中的值。你能告诉我最好的方法是什么吗

我现在使用switch语句调用基于HashMap键的方法,但我想知道是否有更好的替代方法

仅供参考,在myItems类中,我实际上有25个变量要设置

public class MainClass{
    BufferedReader br = new BufferedReader(new FileReader(file));
    String[] datakey = br.readLine().split(";"); // getting header, 25 of them
    HashMap<String,String> bookmap = new HashMap<String,String>();
    String[] dataarr = line.split(";"); // getting values, 25 of them
    int k = 0;
    for(String d : datakey){
        bookmap.put(d, dataarr[k++]); // Key-Value Pair
    }
    myItems item = new myItems(bookmap); // HOW TO WRITE THIS CONSTRUCTOR?
}


public class myItems {
    String _id="";
    String _name="";
    String _genre="";
    String _language="";
    int _rating=0;
    int _price=0;
    ...........................
    ...//25 OF THEM...
    ...........................


    public myItems(HashMap<String,String> allrec){
        Iterator<Map.Entry<String,String>> it = allrec.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry pairs = (Map.Entry)it.next();
            Switch(pairs.getKey()){
                case "id":
                    setid(pairs.getValue());
                    break;
                case "name":
                    setname(pairs.getValue());
                    break;
                Deafult:
                    break;
            }
        }
    }


    public int getid(){
        return this._id;
    }
    public String getname(){
        return this._name;
    }
    ..............................
    ..............................
    ..............................

    public void setid(int id){
        this._id = id;
    }
    public void setname(String name){
        this._name = name;
    }
    ..............................
    ..............................
    ..............................
}
public类MainClass{
BufferedReader br=新的BufferedReader(新文件读取器(文件));
String[]datakey=br.readLine().split(;”;//获取标题,其中25个
HashMap bookmap=新建HashMap();
String[]dataarr=line.split(;”;//获取值,其中25个
int k=0;
for(字符串d:datakey){
bookmap.put(d,dataarr[k++]);//键值对
}
myItems item=newmyitems(bookmap);//如何编写此构造函数?
}
公共类myItems{
字符串_id=“”;
字符串_name=“”;
字符串_quare=“”;
字符串_language=“”;
int _评级=0;
国际价格=0;
...........................
…其中25个。。。
...........................
公共myItems(HashMap allrec){
迭代器it=allrec.entrySet().Iterator();
while(it.hasNext()){
Map.Entry pairs=(Map.Entry)it.next();
开关(pairs.getKey()){
案例“id”:
setid(pairs.getValue());
打破
案例“名称”:
setname(pairs.getValue());
打破
迪福尔特:
打破
}
}
}
公共int getid(){
返回此。\u id;
}
公共字符串getname(){
返回此。\u名称;
}
..............................
..............................
..............................
公共无效集合id(内部id){
这个。_id=id;
}
公共void集合名(字符串名){
这个。_name=name;
}
..............................
..............................
..............................
}

为什么不这样写:

public myItems(HashMap<String,String> allrec){
    setid(allrec.get("id");
    setname(allrec.get("name");
}
private Map<String, String> mAttributes;
public myItems(HashMap<String, String> allrec) {
       mAttributes = allrec; 
} 
public void setId(String id) {
        mAttributes.put("id", id);
}
public String getId() {
        return mAttributes.get("id");
}
import java.lang.reflect.Method;

public void setAll(final Map<String, String> fieldMap) {
    for (final Map.Entry<String, String> entry : fieldMap.entrySet())
        setField(entry);
}
public void setField(final Map.Entry<String, String> entry) {
    setField(entry.getKey(), entry.getValue());
}
public void setField(final String name, final String value) {
    final Method fieldSetter = getFieldSetter(name);
    if (fieldSetter != null) {
        fieldSetter.invoke(this, value);
        return;
    }
    final Field field = getField(name);
    if (field != null) {
        field.set(this, value);
        return;
    }
    // Throw some exception
}
public Method getFieldSetter(final String fieldName) {
    return getMethod(getSetterName(fieldName));
}
public static String getSetterName(final String fieldName) {
    return "set" + upperCaseFirst(fieldName);
}
public static String upperCaseFirst(final String s) {
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public Method getMethod(final String methodName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    try {
        return clazz.getDeclaredMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    return null;
}
public Field getField(final String fieldName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    try {
        return clazz.getDeclaredField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    return null;
}
您的get方法如下所示:

public myItems(HashMap<String,String> allrec){
    setid(allrec.get("id");
    setname(allrec.get("name");
}
private Map<String, String> mAttributes;
public myItems(HashMap<String, String> allrec) {
       mAttributes = allrec; 
} 
public void setId(String id) {
        mAttributes.put("id", id);
}
public String getId() {
        return mAttributes.get("id");
}
import java.lang.reflect.Method;

public void setAll(final Map<String, String> fieldMap) {
    for (final Map.Entry<String, String> entry : fieldMap.entrySet())
        setField(entry);
}
public void setField(final Map.Entry<String, String> entry) {
    setField(entry.getKey(), entry.getValue());
}
public void setField(final String name, final String value) {
    final Method fieldSetter = getFieldSetter(name);
    if (fieldSetter != null) {
        fieldSetter.invoke(this, value);
        return;
    }
    final Field field = getField(name);
    if (field != null) {
        field.set(this, value);
        return;
    }
    // Throw some exception
}
public Method getFieldSetter(final String fieldName) {
    return getMethod(getSetterName(fieldName));
}
public static String getSetterName(final String fieldName) {
    return "set" + upperCaseFirst(fieldName);
}
public static String upperCaseFirst(final String s) {
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public Method getMethod(final String methodName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    try {
        return clazz.getDeclaredMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    return null;
}
public Field getField(final String fieldName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    try {
        return clazz.getDeclaredField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    return null;
}
你可以使用反射。想象一下,一些字段有setter(对于数据结构来说是可以的,对于类来说是有问题的——那么可变性和不可变性呢?),而其他字段没有。然后你可以这样做:

public myItems(HashMap<String,String> allrec){
    setid(allrec.get("id");
    setname(allrec.get("name");
}
private Map<String, String> mAttributes;
public myItems(HashMap<String, String> allrec) {
       mAttributes = allrec; 
} 
public void setId(String id) {
        mAttributes.put("id", id);
}
public String getId() {
        return mAttributes.get("id");
}
import java.lang.reflect.Method;

public void setAll(final Map<String, String> fieldMap) {
    for (final Map.Entry<String, String> entry : fieldMap.entrySet())
        setField(entry);
}
public void setField(final Map.Entry<String, String> entry) {
    setField(entry.getKey(), entry.getValue());
}
public void setField(final String name, final String value) {
    final Method fieldSetter = getFieldSetter(name);
    if (fieldSetter != null) {
        fieldSetter.invoke(this, value);
        return;
    }
    final Field field = getField(name);
    if (field != null) {
        field.set(this, value);
        return;
    }
    // Throw some exception
}
public Method getFieldSetter(final String fieldName) {
    return getMethod(getSetterName(fieldName));
}
public static String getSetterName(final String fieldName) {
    return "set" + upperCaseFirst(fieldName);
}
public static String upperCaseFirst(final String s) {
    return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
public Method getMethod(final String methodName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    try {
        return clazz.getDeclaredMethod(methodName, String.class);
    } catch (final NoSuchMethodException ignore) { }
    return null;
}
public Field getField(final String fieldName) {
    final Class<?> clazz = getClass();
    try {
        return clazz.getField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    try {
        return clazz.getDeclaredField(fieldName);
    } catch (final NoSuchFieldException ignore) { }
    return null;
}
import java.lang.reflect.Method;
公共void setAll(最终地图字段地图){
对于(最终映射。条目:fieldMap.entrySet())
设置字段(输入);
}
公共无效设置字段(最终映射条目){
setField(entry.getKey(),entry.getValue());
}
公共void设置字段(最终字符串名称、最终字符串值){
最终方法fieldSetter=getFieldSetter(名称);
if(fieldSetter!=null){
调用(这个值);
返回;
}
最终字段=getField(名称);
如果(字段!=null){
字段.set(此字段,值);
返回;
}
//抛出一些异常
}
公共方法getFieldSetter(最终字符串fieldName){
返回getMethod(getSetterName(fieldName));
}
公共静态字符串getSetterName(最终字符串字段名){
返回“set”+大写字母优先(fieldName);
}
公共静态字符串大写优先(最终字符串s){
返回字符.toUpperCase(s.charAt(0))+s.substring(1);
}
公共方法getMethod(最终字符串methodName){
最终类clazz=getClass();
试一试{
返回clazz.getMethod(methodName,String.class);
}catch(最终NoSuchMethodException忽略){}
试一试{
返回clazz.getDeclaredMethod(methodName,String.class);
}catch(最终NoSuchMethodException忽略){}
返回null;
}
公共字段getField(最终字符串字段名){
最终类clazz=getClass();
试一试{
返回clazz.getField(fieldName);
}catch(最终NoSuchFieldException忽略){}
试一试{
返回clazz.getDeclaredField(fieldName);
}catch(最终NoSuchFieldException忽略){}
返回null;
}
  • 有一些异常需要处理,您需要相应地更改源代码
  • Android Reflection上的AFAIR将受到性能惩罚。您可能需要关注该方法的性能

顺便说一句,您可能应该坚持Java命名约定,将类命名为MyItems而不是MyItems。我之所以迭代,是因为并非所有字段都会一直出现。可能在某些调用中没有“name”键。无论如何,我主要关心的是,如果我有25-30个set方法,是否可以优化代码而不是手动编写这30个方法?如果map没有键,那么map.get(Object)将返回null。然后,您只需要检查null指针的返回值。从技术上讲,您可能可以使用reflect并根据类的名称(如字符串中)查找类的方法。在这种情况下,您可能会将密钥命名为与方法名相同的名称。但我反对这样做。在表现方面,你不会得到任何好处。可能在可读性方面也没有什么。无论您以何种方式编写它,如果agttribute在映射中为null或不存在,它都将为null。我认为您可能根本不需要使用任何字段。把所有的东西都存储在地图上。详情见下面我的回答。