gpt4 book ai didi

java - 从字符串到泛型的转换

转载 作者:搜寻专家 更新时间:2023-11-01 01:26:14 25 4
gpt4 key购买 nike

我需要将字符串转换为变量值。我只为 C# 找到了解决方案。我需要它在 Java 中。

public class Property<T> {

T value;

public void setValue(String input){
if(value instanceof String){
value= input; // value is type of T not type of string (compilation error)
// incompatible types: String cannot be converted to T
}
if(value instanceof int){
//parse string
}
if(value instanceof boolean){
//parse string
}
...
}
}

最佳答案

这不是它的工作原理。但是,您可以使用多态性来获得有用的结果。

多态性解决方案

基本通用(和抽象)属性

public abstract class Property<T> {
T value;
public abstract void setValue(String input);
}

字符串属性

public class StringProperty extends Property<String> {
@Override
public void setValue(String input) {
this.value = input;
}
}

整数属性

public class IntegerProperty extends Property<Integer> {
@Override
public void setValue(String input) {
this.value = Integer.valueOf(input);
}
}

不确定您的实际目标是什么,但这种方法可能有效。

请注意,input instanceof T会失败,因为类型删除。这是行不通的。


解决方案 Class<T>作为参数

为了详细说明您的方法,这会起作用 - 但它很丑陋。

丑陋且不太方便。不知道你为什么想要它,tbh。

class Property<T> {

public T value;
private final Class<T> clazz;

public Property(Class<T> clazz) {
super();
this.clazz = clazz;
}

@SuppressWarnings("unchecked")
public void setValue(String input) {
if (clazz.isAssignableFrom(String.class)) {
value = (T) input;
} else if (clazz.isAssignableFrom(Integer.class)) {
value = (T) Integer.valueOf(input);
} else if (clazz.isAssignableFrom(Boolean.class)) {
value = (T) Boolean.valueOf(input);
} else if (clazz.isAssignableFrom(Double.class)) {
value = (T) Double.valueOf(input);
} else {
throw new IllegalArgumentException("Bad type.");
}
}
}

这样使用:

Property<String> ff = new Property<>(String.class);
ff.setValue("sdgf");

Property<Integer> sdg = new Property<>(Integer.class);
sdg.setValue("123");

System.out.println(ff.value);
System.out.println(sdg.value);

解决方案 Reflection

显然,可以找出用于实例化属性的参数。

这个神奇的小公式给了你:

(Class<?>) getClass().getTypeParameters()[0].getBounds()[0]

我什至不知道我是怎么找到它的。好了,我们开始吧:

class Property<T> {

T value;

@SuppressWarnings("unchecked")
public void setValue(String input)
{
// BEHOLD, MAGIC!
Class<?> clazz = (Class<?>) getClass().getTypeParameters()[0].getBounds()[0];

if (clazz.isAssignableFrom(String.class)) {
value = (T) input;
} else if (clazz.isAssignableFrom(Integer.class)) {
value = (T) Integer.valueOf(input);
} else if (clazz.isAssignableFrom(Boolean.class)) {
value = (T) Boolean.valueOf(input);
} else if (clazz.isAssignableFrom(Double.class)) {
value = (T) Double.valueOf(input);
} else {
throw new IllegalArgumentException("Bad type.");
}
}
}

别看我,我不会用那个。我有一些常识。

关于java - 从字符串到泛型的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24589495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com