Java 设置名称时发生类强制转换异常
我在设置名称时遇到强制转换异常Java 设置名称时发生类强制转换异常,java,Java,我在设置名称时遇到强制转换异常 Object[] customers= customerRepository.getCustomerName(Id); Customer row = new Customer(); row.setName((String) customers[0]+" "+(String) customers[1]); 例外情况是: HTTP Status 500 - Request process
Object[] customers= customerRepository.getCustomerName(Id);
Customer row = new Customer();
row.setName((String) customers[0]+" "+(String) customers[1]);
例外情况是:
HTTP Status 500 - Request processing failed;
nested exception is java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to java.lang.String
根据例外情况,数组中存储的对象不是String类型 您可以使用他们的
toString()
方法:
row.setName(customers[0].toString()+" "+customers[1].toString());
与其执行字符串类型转换,不如直接执行.toString()?使用
customers[0]是否更好?getCustomerName(Id)
返回一个对象数组。我在这个世界上迷失了方向。因此,最终我的客户名将是NameIdRoleAndWhatNot
@sᴜʀᴇsʜᴀᴛᴛᴀ 如果那是OP想要的,那就是他/她将得到的。如果OP想要从对象获取特定属性,那么没有任何东西可以阻止他/她这样做。
row.setName(((String) customers)[0]+" "+((String) customers)[1]);