如何将String强制转换为Java中的Class实例?

 收藏

我试图使处理用户输入变得容易,所以我制作了这个“设置”系统。当用户键入其值时,如何确定它是诸如布尔值之类的类的实例?我不确定“ casting”是否正确。更像是检查它是否是实例。我将要进行很多设置,所以我不确定是否有更好的方法来制作这样的系统。

在“ handleUserInput()”中的注释中查找。

package com.hobbercode.test;

import java.util.ArrayList;

public final class Test {

    private static ArrayList<Setting> settings = new ArrayList<Setting>();

    public static void main(String[] args) {
        // Register settings
        settings.add(new Setting("pepperoni", Boolean.class)); // name, type
        settings.add(new Setting("thinCrust", Boolean.class));
        settings.add(new Setting("squareCut", Boolean.class));
        settings.add(new Setting("amountOfCheese", Integer.class));

        handleUserInput(args);

        System.out.println("Pepperoni: " + getSettingByName("pepperoni").getValue());
        System.out.println("ThinCrust: " + getSettingByName("thinCrust").getValue());
        System.out.println("SqaureCut: " + getSettingByName("squareCut").getValue());
        System.out.println("AmountOfCheese: " + getSettingByName("amountOfCheese").getValue());
    }

    private static void handleUserInput(String[] args) {
        String name = args[0];
        String value = args[1];

        Setting setting = getSettingByName(name);
        Class<?> type = setting.getType();

        // How do I make sure "value" is of type "type" and cast it to an object?
        // Ex: value = true
        //     type  = Boolean.class

        // setting.setValue(castedValue)
    }

    private static Setting getSettingByName(String name) {
        for(Setting setting : settings) {
            if(setting.getName().equalsIgnoreCase(name))
                return setting;
        }
        return null;
    }

    public static final class Setting {

        private final String name;
        private final Class<?> type;
        private Object value;

        public Setting(String name, Class<?> type) {
            this.name = name;
            this.type = type;
        }

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

        public String getName() {
            return name;
        }

        public Class<?> getType() {
            return type;
        }

        public Object getValue() {
            return value;
        }

    }

}

回复