gpt4 book ai didi

Java:如何从类型A转换为类型B?

转载 作者:行者123 更新时间:2023-12-02 06:08:38 25 4
gpt4 key购买 nike

我是一名 Java 初学者,虽然我在这里和 Google 上都寻找过这个主题,但我还没有找到。我确信它一定在某个地方,但我不知道如何搜索。无论如何,这就是:

如何编写从 string/int/etc 进行转换的方法。到一个类(class),反之亦然?我绝对希望我的类转换是自动的,但我可以忍受不太完美的类型转换。我不喜欢调用 class("some string") 或 class.toString() 来从字符串到类来回转换。我希望它尽可能无缝。这是一个例子:

我有一个 IsFound 类,其行为类似于 boolean 值,我将其用作方法中的返回类型;在方法主体中,我返回一个类似“found”的字符串(而不是true)。您可能会 mock 我没有使用 boolean 值,但我想玩一下自定义类/类型。这是一些代码

public class IsFound{

public boolean found; // field

public IsFound(String isFound_){
if(isFound_.equals("FOUND")){
found = true;
else found = false;
}
}

public String toString(){
if(found) return "found";
else return "not found";
}
}

这是我能到达的最远距离。我需要与字符串之间的转换器方法,为了将来的引用,我想知道这些转换器是否适用于 int、char 甚至其他类。

扩展 Boolean 的解决方案只是作为最后的手段,因为我不知道我正在携带什么膨胀 - 我想从 0 开始自己创建该类。编辑:我希望能够使用类似的东西:

public IsFound parse(String substring_){
if(search(substring_, string) == true){
return FOUND; // or return "FOUND";
{
return NOTFOUND; // or return "NOT FOUND";
{

目前它给出了无法从 String 转换为 IsFound 的错误。我想填补这个空白。

最佳答案

我还会使用枚举,这里的枚举可以为您提供类中的所有功能。

  public enum IsFound{
// each of these definitions are like calls to the IsFound constructor below
FOUND("found"),
NOT_FOUND("not found");

// string representation
private final String toString;

private IsFound(String isFound){
this.toString = isFound;
}

/**
* @Override
*/
public String toString(){
return toString;
}


// I think this is what you want. I'm not sure why you need this, but
// am including it as I think it gives you what you want. see example below
public static IsFound convert( String foundString ){
if( FOUND.toString.equals(foundString) ){
return FOUND;
}
else if( NOT_FOUND.toString.equals(foundString) ){
return NOT_FOUND;
}
else{
return null;
}
}
}

您可以通过以下方式使用它:

private IsFound myFoundValue;

myFoundValue = IsFound.FOUND;

System.out.println(myFoundValue.toString()); // "found"

myFoundValue = IsFound.NOT_FOUND;

System.out.println(myFoundValue.toString()); // "not found"

switch( myFoundValue ){
case FOUND:
System.out.println("the value is FOUND");
break;
case NOT_FOUND:
System.out.println("the value is NOT_FOUND");
break;
default:
System.out.println("this should never happen");
break;
}

myFoundValue = IsFound.convert("found"); // IsFound.FOUND

System.out.println( myFoundValue.toString() ); // "found"

关于Java:如何从类型A转换为类型B?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22077453/

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