不兼容的类型:对象不能在 java netbeans 中转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42201076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incompatible types : Object cant not be converted to String in java netbeans
提问by user3518835
I'm trying to use object Array in my project and i get an error :
我试图在我的项目中使用对象数组,但出现错误:
incompatible types: Object cannot be converted to String
on this line :
在这一行:
ST1 = new String[]{emt1, emt2, emt3, emt4};
Now i don't figure out what is the cause of this error . please help me .
现在我不知道这个错误的原因是什么。请帮我 。
Object[] ST1;
Object emt1,emt2,emt3,emt4;
private void jButton3ActionPerformed(ActionEvent evt) {
try {
emt1 = null;
emt2 = null;
emt3 = null;
emt4 = null;
ST1 = new String[]{emt1, emt2, emt3, emt4};
}
....
回答by YCF_L
You have two way one is to cast every Object emt1, emt2, .. to String like this :
您有两种方法,一种是将每个 Object emt1, emt2, .. 转换为 String ,如下所示:
ST1 = new String[]{(String)emt1, (String)emt2, (String)emt3, (String)emt4};
Or you should to change the type of your attribute:
或者你应该改变你的属性类型:
Object emt1, emt2, emt3, emt4;
To String
到字符串
String emt1, emt2, emt3, emt4;
ST1 = new String[]{emt1, emt2, emt3, emt4};
回答by anacron
You have declared emt1,emt2,emt3,emt4
as Object
. In the last line where you are creating the assigning the array to the variable ST1
, you are creating a String
array and storing Object
intances in it. This is what is causing the problem.
您已声明emt1,emt2,emt3,emt4
为Object
。在创建将数组分配给变量的最后一行中ST1
,您正在创建一个String
数组并Object
在其中存储实例。这就是导致问题的原因。
If you wish to use the objects in this manner and if you are sure that the emt1,emt2,emt3,emt4
objects are all strings, you can add a cast to your code like this:
如果您希望以这种方式使用这些对象,并且您确定这些emt1,emt2,emt3,emt4
对象都是字符串,您可以像这样在代码中添加一个强制转换:
ST1 = new String[] { (String) emt1, (String) emt2, (String) emt3, (String) emt4 };
This should work.
这应该有效。
回答by Thorbj?rn Ravn Andersen
A String is an Object, but an Object is not necessarily a String.
字符串是对象,但对象不一定是字符串。
You try to use variables which are Objects where the compiler expects Strings, and the compiler tells you so. Perhaps the emt1, emt2, emt3 and emt4 variables should have been declared as String? (Hard to tell from the snippet given).
您尝试使用编译器需要字符串的对象变量,编译器会告诉您。也许 emt1、emt2、emt3 和 emt4 变量应该被声明为 String?(很难从给出的片段中看出)。