简体   繁体   中英

Casting Interface to Class in Java

In Java there is a method that has a parameter, and this parameter is an Interface. Using such method can I do a cast to a concrete class?

How can I calculate the cost of this cast performance-wise?

Example - casting Interface to Class:

public void convertToClass(IUser iu) {          
        User u = (User) iu;
}

Like said in a comment, in practice it's not a matter of performance, but of expressing your intent: if you require a specific class, you should require that, not an interface. However, often the case is that you can require an interface and then operate through that interface, omitting the cast altogether. This is also how it usually should be done. You should explore that possibility.

As to the actual question: the cast has some overhead, but it shouldn't matter in pretty much any use case. The overhead comes from checking if the cast is possible and throwing an exception if it is not. If you're interested in further discussion about the overhead of casting, you can read more about it here . If you wan't to measure the overhead, you should use methods outlined in How do I write a correct micro-benchmark in Java?

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