简体   繁体   中英

Java: Can't assign MyClass to Object type?

So I'm doing an Android app, and I've added the a tag to a view through:

view.setTag(1,myClass);

Now I want to get that tag through this:

myClass = view.getTag(1);

But it says:

Incopatible types

Required: MyClass

Found: java.lang.Object

Yes, I've declared myClass before...

So, how can I make MyClass be able to be "created" or "assigned" from an Object? Such as Strings and Integers.

Thanks in advance.

简单地投下它。

myClass = (MyClass) view.getTag(1);

As you can see here the return type of getTag(int i) is Object . One option is to cast the returned object to the type that you expect.

Object obj = view.getTag(1);

if(obj instanceOf MyClass){
    MyClass myClass = (MyClass) obj;
}

However,if you only need to store the class type, the following is a little more interesting:

MyClass myInstance = new MyClass();

view.setTag(1, myInstance);

Class type = view.getTag(1).getClass();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM