请用java代码实现范型对象转string
时间: 2024-02-03 21:04:01 浏览: 45
假设有一个泛型类MyClass,其中包含一个泛型变量T,可以通过以下代码将MyClass<T>对象转化为String类型:
```java
public class MyClass<T> {
private T variable;
public MyClass(T variable) {
this.variable = variable;
}
public T getVariable() {
return variable;
}
public void setVariable(T variable) {
this.variable = variable;
}
@Override
public String toString() {
return "MyClass{" +
"variable=" + variable +
'}';
}
}
public class Main {
public static void main(String[] args) {
MyClass<Integer> obj = new MyClass<>(123);
String str = obj.toString();
System.out.println("转化后的字符串为:" + str);
}
}
```
输出结果为:
```
转化后的字符串为:MyClass{variable=123}
```
在MyClass类中,由于T需要实现toString()方法,因此在toString()方法中可以直接调用T的toString()方法将其转化为String类型。在main函数中,创建一个MyClass<Integer>对象,并将其转化为String类型,最终输出转化后的字符串。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)