这是将ArrayList从服务器发送到客户端的程序的一部分.我想删除有关此代码中最后一行的警告:
客户代码:
Socket s;
(...)
// A server is sending a list from the other side of the link.
ois = new ObjectInputStream(s.getInputStream());
MyList = (ArrayList<MyVariable>) ois.readObject();
Run Code Online (Sandbox Code Playgroud)
MyVariable是一个具有一些属性的Java类.服务器正在创建一个ArrayList并用MyVariable变量填充它作为项目.然后它将完整列表发送给客户端.
我想知道为什么我会在那里发出警告以及如何完美编码以获得0警告.如果有可能我想避免使用"@SuppressWarnings("unchecked")".;)
谢谢,
路易斯
我有一个接受Object的方法.在一个用例中,该方法接受a HashMap<String, String>并将每个值设置为相应键名的属性.
public void addHelper(Object object) {
if (object instanceof HashMap) {
HashMap<String, String> hashMap = (HashMap<String, String>) object;
this.foo = hashMap.get("foo");
this.bar = hashMap.get("bar");
}
}
Run Code Online (Sandbox Code Playgroud)
此类遵循特定接口,因此不能为这些属性添加setter.
我的问题是,如何检查此处的类型?
HashMap<String, String> hashMap = (HashMap<String, String>) object;
Run Code Online (Sandbox Code Playgroud)
提前致谢!
解
感谢@drobert的回答,这是我的更新代码:
public void addHelper(Object object) {
if (object instanceof Map) {
Map map = (Map) object;
if (map.containsKey("foo")) this.foo = map.get("foo").toString();
if (map.containsKey("bar")) this.bar = map.get("bar").toString();
}
}
Run Code Online (Sandbox Code Playgroud) 我试图理解为什么这段代码有一个未经检查的强制警告.前两个演员没有警告,但第三个演员:
class StringMap<V> extends HashMap<String, V> {
}
class StringToIntegerMap extends HashMap<String, Integer> {
}
Map<?, ?> map1 = new StringToIntegerMap();
if (map1 instanceof StringToIntegerMap) {
StringToIntegerMap stringMap1 = (StringToIntegerMap)map1; //no unchecked cast warning
}
Map<String, Integer> map2 = new StringMap<>();
if (map2 instanceof StringMap) {
StringMap<Integer> stringMap2 = (StringMap<Integer>)map2; //no unchecked cast warning
}
Map<?, Integer> map3 = new StringMap<>();
if (map3 instanceof StringMap) {
StringMap<Integer> stringMap3 = (StringMap<Integer>)map3; //unchecked cast warning
}
Run Code Online (Sandbox Code Playgroud)
这是stringMap3演员阵容的完整警告:
类型安全:未经检查强制
Map<capture#3-of ?,Integer> …
我在 Android 应用程序中使用 ViewModelFactory 将一些数据从 Fragment 传递到我的 ViewModel。我收到未经检查的演员警告。如果我使用 Supress,警告就会消失。我想知道有没有办法在不使用 Supress("UNCHECKED_CAST") 的情况下处理这个问题
我用来创建 ViewModelFactory 的代码
val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
//factory to pass necessary data to ViewModel
@NonNull
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return activity?.application?.let {
BookReaderViewModel(
it,
"local",//todo:remote or local book. value will come from arguments
1//todo: bookId will come from arguments
)
} as T
}
}
Run Code Online (Sandbox Code Playgroud)
因为 T 收到了警告。
我有以下测试代码:
FileSystem fs = FileSystems.getDefault();
Path conf = fs.getPath(".");
WatchKey key = null;
try {
WatchService watcher = fs.newWatchService();
conf.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
while(true) {
key = watcher.take(); // waits
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (StandardWatchEventKinds.OVERFLOW == kind) continue;
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path file = ev.context();
System.out.println(file);
}
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e.getMessage(), e);
}
Run Code Online (Sandbox Code Playgroud)
编译器unchecked cast发出与该行相关的警告
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Run Code Online (Sandbox Code Playgroud)
因为作为一个event出来,编译器无法判断在运行时它是否真的要包含一个,而不是其他东西.key.pollEvents()WatchEvent<?>Path …
使用此代码:
public class DowncastTest {
public static void main(String[] args) {
try {
System.out.println(1);
} catch (Exception ex) {
Throwable cause = ex.getCause();
if (cause != null) {
Exception exCause = (Exception)cause;
System.out.println(exCause);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么javac没有给出未经检查的演员警告?
Exception扩展Throwable,所以你不能只将所有Throwables 转换为Exception.
我认为这(String)x是一个未经检查的演员,但编译器没有给出任何警告.为什么会这样?
public static void main(String[] args) {
Object x=new Object();
String y=(String)x;
}
Run Code Online (Sandbox Code Playgroud) 执行下面的代码时,代码执行完美而没有任何错误,但对于类型的变量,方法List<Integer>的返回类型get()应该是Integer,但是在执行此代码时,当我调用x.get(0)一个字符串时返回,而这应该抛出一个例外.
public static void main(String[] args)
{
ArrayList xa = new ArrayList();
xa.addAll(Arrays.asList("ASDASD", "B"));
List<Integer> x = xa;
System.out.println(x.get(0));
}
Run Code Online (Sandbox Code Playgroud)
但是在执行下面的代码时,只需将返回对象的类检索添加到前一个代码块就会引发类强制转换异常.如果上面的代码完美执行,则以下内容也应该执行而没有任何异常:
public static void main(String[] args)
{
ArrayList xa = new ArrayList();
xa.addAll(Arrays.asList("ASDASD", "B"));
List<Integer> x = xa;
System.out.println(x.get(0).getClass());
}
Run Code Online (Sandbox Code Playgroud)
为什么java在获取对象的类类型时执行类型转换?
对于一个类,我被分配Vehicle使用 ObjectInputStream ( in)编写代码以读取类的对象。对象存储在名为 的 ArrayList 中orders。
SSCE:
// Read all orders
Object obj = in.readObject();
orders = (ArrayList<Vehicle>) obj;
Run Code Online (Sandbox Code Playgroud)
但是,编译器抱怨:
MacBook:Homework Brienna$ javac Orders.java -Xlint:unchecked
Orders.java:152: warning: [unchecked] unchecked cast
orders = (ArrayList<Vehicle>) in.readObject();
^
required: ArrayList<Vehicle>
found: Object
1 warning
Run Code Online (Sandbox Code Playgroud)
我总是尝试改进我的代码,而不是忽略或抑制警告。在这种情况下,我想出了一个解决方案,但我试图了解它为什么有效,以及是否有更好的解决方案。
此更新停止警告:
// Read all orders, casting each order individually
Object obj = in.readObject();
ArrayList ar = (ArrayList) obj;
for (Object x : ar) {
orders.add((Vehicle) x);
}
Run Code Online (Sandbox Code Playgroud)
根据我从我阅读的内容中了解到的内容,它可以工作,因为(ArrayList<Vehicle>) obj如果不是所有元素都是Vehicle …
private static transient JavaPlugin myPlugin = null;
public SomeClass(JavaPlugin plugin) {
if (myPlugin == null) myPlugin = plugin;
}
public <T> T getPlugin(Class<? extends JavaPlugin> plugin) {
return (T)myPlugin; // return casted version of "myPlugin" form above
}
Run Code Online (Sandbox Code Playgroud)
在下面的行中调用它可以正常工作,并且尝试使用不扩展JavaPlugin的类将引发编译时错误.但是我怎样才能使上述功能无需工作呢@SuppressWarnings("unchecked")?
MyPlugin nc = this.getPlugin(my.main.package.MyPlugin.class);
Run Code Online (Sandbox Code Playgroud) 以下代码Unchecked cast: 'T' to 'U'在 IntelliJ IDEA 中生成警告:
interface A {}
class B<T extends A, U extends A> {
void f() {
final T t = null;
final U u = (U) t;
}
}
Run Code Online (Sandbox Code Playgroud)
这对我来说没有意义,因为T和U被定义为相同的类型。问题是什么?
在一个应用程序中,我正在使用SharedPrefernces保存/加载(序列化/反序列化)某些对象。
这是反序列化代码:
private void loadData() {
String str = sharedPreferences.getString(PREF_TAG, null);
byte[] bytes = Base64.decode(str, Base64.DEFAULT);
try {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream input = new ObjectInputStream(bais);
arrayOfObjects = (ArrayList<MyObject>) input.readObject();
} catch (Exception e) {
Log.i("BUG", "error decoding serialized objects: " + e.toString());
}
if (arrayOfObjects == null) {
Log.i("BUG", "serious problem!");
}
}
Run Code Online (Sandbox Code Playgroud)
但是每当我编译该项目时,该行:
arrayOfObjects = (ArrayList<MyObject>) input.readObject();
Run Code Online (Sandbox Code Playgroud)
引起警告,包含此方法的类“使用未经检查或不安全的操作”。
如何摆脱此警告或更改代码以更安全?