When should I use the java 5 method cast of Class?
Looking through some code I came across the following code
trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));
and I'd like to know if casting this way has any advantages over
trTuDocPackTypdBd.update((TrTuDocPackTypeDto)packDto);
I've asked the developer responsible and he said he used it because it was new (which doesn't seem like a particularly good reason to me), but I'm intrigued when I would want to use the method.
Asked by: First Name760 | Posted: 28-01-2022
Answer 1
These statements are not identical. The cast method is a normal method invocation (invokevirtual
JVM instruction) while the other is a language construct (checkcast
instruction). In the case you show above, you should use the second form: (TrTuDocPackTypeDto) packDto
The cast
method is used in reflective programming with generics, when you have a Class instance for some variable type. You could use it like this:
public <T> Set<T> find(Class<T> clz, Filter criteria) {
List<?> raw = session.find(clz, criteria); /* A legacy, un-generic API. */
Set<T> safe = new HashSet<T>();
for (Object o : raw)
safe.add(clz.cast(o));
return safe;
}
This gives you a safe way to avoid the incorrect alternative of simply casting a raw type to a generic type:
/* DO NOT DO THIS! */
List raw = new ArrayList();
...
return (List<Widget>) raw;
The compiler will warn you, Unchecked cast from List to List<Widget>
, meaning that in the ellipsis, someone could have added a Gadget
to the raw list, which will eventually cause a ClassCastException
when the caller iterates over the returned list of (supposed) Widget
instances.
Answer 2
The main case for doing it (IME) is when you need to safely cast in a generic class/method. Due to type erasure, you can't cast to T
but if you've been provided a Class<? extends T>
parameter then you can use that to cast and the result will be assignable to a variable of type T
.
Answer 3
I can't find an example where the cast method is possible and the cast syntax not. However, looking at the code, it seems that in case the cast is not possible, the cast method throws a ClassCastException with no type information attached, whereas the cast syntax will give you some hints (as in, "could not cast Snoopy to TyrannosorusRex") :
/**
* Casts an object to the class or interface represented
* by this <tt>Class</tt> object.
*
* @param obj the object to be cast
* @return the object after casting, or null if obj is null
*
* @throws ClassCastException if the object is not
* null and is not assignable to the type T.
*
* @since 1.5
*/
public T cast(Object obj) {
if (obj != null && !isInstance(obj))
throw new ClassCastException();
return (T) obj;
}
Answered by: Roland309 | Posted: 01-03-2022
Answer 4
With the first form
trTuDocPackTypdBd.update(TrTuDocPackTypeDto.class.cast(packDto));
you can do this:
public void dynamicCast( Class clazz, Object o ) {
this.x = clazz.cast( o );
}
With the second you can't. The casting class should be hard coded.
Why would you use a variable to cast in first place? That's another question. :) The first thing that comes to mind is, you don't know ( at compile time ) the class that will be casted to.
Answered by: Edgar586 | Posted: 01-03-2022Answer 5
Both of these statements are identical. Pick whichever one you find more readable. The second method is more common in my experience, and it is the once that I prefer.
I tend to use the cast method solely when I am working with reflection, and it reads nicer in that situation. All other times I find myself using the second way of casting.
Answered by: Julia723 | Posted: 01-03-2022Similar questions
class - Why can't java find my method?
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?
What is the reason code such as the example below does not compile?
Thank you,
class a {
public static void myMethod(Object myObj) {
myObj.testing();
}
}
class b {
public void testing() {
System.out.println ("TEST...
class and method in java
i m jst confused that which of the two exists in the memory a class or the object?
class - Why can't java find my method?
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?
What is the reason code such as the example below does not compile?
Thank you,
class a {
public static void myMethod(Object myObj) {
myObj.testing();
}
}
class b {
public void testing() {
System.out.println ("TEST...
class and method in java
i m jst confused that which of the two exists in the memory a class or the object?
class or method alias in java
I have long java class and method names
LONGGGGGGGGGGGGGGGClass.longggggggggggggggggggggggggMethod();
I want to alias it to
g.m(); in another class
can this be done?
How do you call the main method of a java class from jruby?
Hi I am using JRuby to interact with a Java class. I have successfully imported the java class into my jruby program and created a new instance. However when I create the instance, I cannot call the main method. I can call every other method like object.method but I can't do object.main. How do I access the main method of a java class through jruby?
java - Get Class name from within a method
I would like to reference a Class's name within a method. In the following example, I would like TestSuite to be printed out. I can put CarsTestSuite.class.getName(), but I'd like to use the method to get the class name so that I never have to edit it. The solution will find the method's class instead of myself filling it in.
public class TestSuite extends TestCase {
public static void ...
java - How to call base class method?
Say I have classes declared like this:
public abstract class IdentifiableEntity {
public boolean validate() {
return true;
}
}
public class PreferenceCategory extends IdentifiableEntity {
public boolean validate() {
return true;
}
}
Now, let's say I have PreferenceCategory variable created, and I want to call the IdentifiableEntity.validate() method,
To make a new method in a class in Java
Hey guys!
I'm new to Java, and I want to make a new class called Student. Now I want every student to have their own grade array. My question is: how do I make a method setGradeArray in the class Student?
Thanks a lot!
How to call a method in another class in Java?
Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.
classroom.java
public class classroom {
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName) {
classRo...
java - How do i specify which class to call a method from
When i run the code below, the fireEvent() method is called inside the Slider class instead of the ColorPanel class. How can i make it call the fireEvent() method in the ColorPanel class? (They both extend EventComponent which has the method)
public class ColorPanel extends EventComponent<ColorChangeListener> {
public ColorPanel() {
...
add(new ValueSlider());
}
......
java - How to call method from different class?
I have 2 classes, Main and DialogOne (an owner class for a dialog ui). In Main, I call new DialogOne().center(); This brings up the dialog box. In DialogOne, I have a clickhandler for a button. When the button is clicked, I insert a record into a database.
Main main = new Main(); //because the db.open is in Main
@UiHandler("addBookButton")
vo...
java - JSTL, Beans, and method calls
I'm working on a JSP where I need to call methods on object that come from a Bean. The previous version of the page does not use JSTL and it works properly. My new version has a set up like this:
<jsp:useBean id="pageBean" scope="request" type="com.epicentric.page.website.PageBean" />
<c:set var="pageDividers" value="<%= pageBean.getPageDividers() %>" />
<c:set var="numColumns" value="$...
java - How can I call a method in an object from outside the JVM?
I have a really simple Java class that effectively decorates a Map with input validation, with the obvious void set() and String get() methods.
I'd like to be able to effectively call those methods and handle return values and exceptions from outside the JVM, but still on the same machine Update: the caller I have in mind is not another JVM; thanks @Dave Ray
My implementation considerations...
java - How to show if a method may return null
After posting this question and reading that one I realized that it is very important to know if a metho...
swing - Java Paint Method Doesn't Paint?
I'm working on a simple little swing component, and I'm tearing out my hair trying to figure out why my paint method isn't working.
The idea behind this component is that it's a small JPanel with a label. The background (behind the label) is supposed to be white, with a colored rectangle on the left-hand side indicating the ratio of two measurements: "actual" and "expected".
If you had a bunch of these comp...
class - Why can't java find my method?
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?
What is the reason code such as the example below does not compile?
Thank you,
class a {
public static void myMethod(Object myObj) {
myObj.testing();
}
}
class b {
public void testing() {
System.out.println ("TEST...
java - Can I mock a super class method call?
Sometimes, you want to test a class method and you want to do an expectation on a call of a super class method. I did not found a way to do this expectation in java using easymock or jmock (and I think it is not possible).
There is a (relative) clean solution, to create a delegate with the super class method logic and then set expectations on it, but I don't know why and when use that solution ¿any ideas/examples?...
Java Main Method, Good Coding Style
Closed. This question is opinion-based. It is not c...
print method in java
I want to ask you about the print vector array , the following one:
Vector[] routingTable = new Vector[connectivity.length];
I tried this method , but it doesn't work with me and it gives me protocol.Route@c17164
when I printed in the main, here is the code, so can you tell me why it doesn't print the correct value ?
public String printRT(int hop)
{
String ...
How can I split up paint swing method in java?
I'm developing a fair sized hospital simulation game in java.
Right now, my pain method is starting to look a little big, and I need a way to split it up into different sections...
I have an idea, but I'm not sure if this is the best way.
It starts by painting the grass, then the hospital building, then any buildings, then people, then any building previews when building. The grass and hospital building will not change, so...
c# - Method name from line number
Given a line number of a particular class source code (Java/C#) - is there an easy way to get the name of the method it falls within? (If it falls within one) (Presumably using an Abstract Syntax Tree)
(This would be useful in limiting the output of checkstyle to just the method touched).
I'm assuming you'd have to use an Abstract Syntax Tree to do Line#->MethodName.
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)