[英]Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?
[英]java instance variable with class name as return type
对于下面的代码,我创建了一个实例变量,其类名称为返回类型
class classtype{
static classtype x;
public static void main(String...a){
System.out.println(x);
}
}
上面的代码输出为null
表明此具有类名作为返回类型的实例变量保存字符串类型值,但是很显然,当我尝试初始化它时
static classtype x="1";
它给出在java.Lang.String
发现的类型不匹配错误
请任何人都可以解释
错误1:
x="1";
你不能这样做
因为Classtype
不是String
类型。
错误2:
打印null
class Classtype{
static Classtype x = new Classtype();
public static void main(String...a){
System.out.println(x);
}
}
确保System.out.println(x);
默认情况下,这里打印Objects toString
方法。
由于您的x
尚未初始化,因此现在为null。
因此,按照每个print ( println
调用print
)方法
打印一个字符串。 如果参数为null,则输出字符串“ null”。 否则,将根据平台的默认字符编码将字符串的字符转换为字节,并以完全write(int)方法的方式写入这些字节。
要打印需要String
ovveride
的toString
的方法Classtype
类。 并遵循Java命名约定。 类名以大写字母开头。
随着所有的代码成为
public class Classtype {
static Classtype x = new Classtype();
public static void main(String...a){
System.out.println(x);
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "This is ClassType toString";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.