Java Extracting out初始化类的私有字段

时间:2017-01-24 16:29:14

标签: java design-patterns

使用内置Java API可以解决以下问题吗? (我希望保留严格的私人访问权限,如图所示)

  1. 我有一个抽象类BaseModel的 n 子类。
  2. 这些子类中的每一个都声明了它们自己的一组私有String字段。
  3. 在子类构造函数中,我希望使用Java Reflection从Map设置私有字段。这个函数的一个例子:

    void setPrivateFields(Map<String, String> fieldsValuesMap) throws NoSuchFieldException, IllegalAccessException {
        for (Map.Entry<String, String> entry : fieldsValuesMap.entrySet()) {
            String fieldName = entry.getKey();
            String fieldValue = entry.getValue();
    
            Field field = this.getClass().getDeclaredField(fieldName);
            field.set(this, fieldValue);
        }
    }
    
  4. 是否有可能提取出我在3)中描述的函数,这样我就不必在子类的所有构造函数中重写算法了?

    class BaseModel {}
    
    class Project extends BaseModel {
        private String name;
        private String type;
    
        public Project(Map<String, String> fieldsValuesMap) {
            setPrivateFields(fieldsValuesMap);
        }
    }
    
    class Task extends BaseModel {
        private String description;
        private String rawDescription;
    
        public Task(Map<String, String> fieldsValuesMap) {
            setPrivateFields(fieldsValuesMap);
        }
    }
    
    class SubTask extends BaseModel {
      ...   
    }
    
    ...
    

2 个答案:

答案 0 :(得分:2)

您只需将其添加到超类中即可。

  listProducts.Remove(curentProduct);
                curentProduct.productName = txtname.Text;
                curentProduct.ProductImage = BitmapSourceToByteArray((BitmapSource)imgPhoto.Source);
                curentProduct.Cat = findCategory(cbCatnewpro.SelectedItem.ToString());
                curentProduct.productCode = txtProductCode.Text;
                curentProduct.productInfo = txtInfo.Text;
                curentProduct.productPrice = txtPrice.Text;
                curentProduct.productTEdada = Convert.ToInt32(txtTedad.Text);
                List<dginfocomper> list = new List<dginfocomper>();
                for (int i = 0; i < dgPro.Items.Count; i++)
                {
                    dginfocomper d = dgPro.Items[i] as dginfocomper;
                    list.Add(d);
                }
                foreach (var item in list)
                {
                    if (item == null)
                        break;
                    foreach (var item1 in curentProduct.ProductsProperties.ToList())
                    {

                        int id = findpropertyId(item.m0);
                        if (id == item1.propertyID)
                        {
                            item1.value = item.m1;
                            break;
                        }
                    }

                }
                int y = list.Count - curentProduct.ProductsProperties.ToList().Count;
                int x = curentProduct.ProductsProperties.ToList().Count - 1;
                for (int i = 0; i < y-1; i++)
                {
                    ProductProperty pp = new ProductProperty();
                    pp.propertyID = findpropertyId(list[x].m0);
                    pp.value = list[x].m1;
                   curentProduct.ProductsProperties.Add(pp);
                    x--;
                }
                listProducts.Add(curentProduct);
                entity.SaveChanges();
                dgRowProFill(curentProduct);
                MessageBox.Show("با موفقیت ثبت شد");

答案 1 :(得分:0)

<强> BaseModel.java

abstract class BaseModel {

}

<强> Project.java

import java.util.Map;

class Project extends BaseModel {
    private String name;
    private String type;

    public Project(Map<String, String> fieldsValuesMap) throws NoSuchFieldException, IllegalAccessException {
        Utils.setPrivateFields(this, fieldsValuesMap);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

<强> Task.java

import java.util.Map;

class Task extends BaseModel {
    private String description;
    private String rawDescription;

    public Task(Map<String, String> fieldsValuesMap) throws NoSuchFieldException, IllegalAccessException {
        Utils.setPrivateFields(this, fieldsValuesMap);
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getRawDescription() {
        return rawDescription;
    }

    public void setRawDescription(String rawDescription) {
        this.rawDescription = rawDescription;
    }
}

<强> Utils.java

import java.lang.reflect.Field;
import java.util.Map;

public class Utils {
    static void setPrivateFields(BaseModel baseModel, Map<String, String> fieldsValuesMap) throws NoSuchFieldException, IllegalAccessException {
        for (Map.Entry<String, String> entry : fieldsValuesMap.entrySet()) {
            String fieldName = entry.getKey();
            String fieldValue = entry.getValue();

            Field field = baseModel.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(baseModel, fieldValue);
        }
    }
}

<强> Main.java

import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        map.put("name", "ABC");
        map.put("type", "XYZ");
        Project project = new Project(map);
        System.out.println(project.getName());
        System.out.println(project.getType());
    }
}