Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you are doing a dynamic cast by using <code>Class.cast()</code> with an argument that you're passing to another function, then at compile time nothing is known about the type that you are passing. This is why you cannot use <code>Horse</code> as the argument type where you define the method, but then call the method using reflection in the way that you are. Your cast does very little except verify that -- as long as you don't get an <code>Exception</code> -- the set you pass in is entirely comprised of members of the <code>Class</code> you pass in the name of.</p> <p>Note that the <code>Class.cast()</code> method was introduced in Java 5, meaning you have access to Generics if you have access to <code>Class.cast()</code>. Generics can help clean things up although they won't solve the problem you are trying to solve.</p> <p>Using a Java 5 <code>for</code> loop you can rewrite your loop as follows:</p> <pre><code> public static void callHorse(Set&lt;?&gt; xSet, String clsName) { try { Class&lt;?&gt; hrt = Class.forName(clsName); for (Object x : xSet) { exam(hrt.cast(x)); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } </code></pre> <p>This version is less cluttered and makes your cast more obvious. You are casting to an entirely arbitrary type. The cast may be to <strong>any</strong> type as long as the class definition can be loaded from the classpath. Thus, if your <code>exam()</code> method takes an argument of <code>Horse</code> then the compiler knows that it cannot guarantee that the call will succeed and the code fails to compile.</p> <p>Even if you try overloading, it won't work. That is, if you create the methods:</p> <pre><code>public static void exam(Object obj) { System.out.println("Object " + obj); } public static void exam(Horse obj) { System.out.println("Horse " + obj); } </code></pre> <p>the <code>exam(Object)</code> method will <strong>always</strong> be the one invoked. Try it.</p> <p>The bottom line is that what you're trying to do cannot be done. You need to give us more information about exactly what your goal is before we can help you.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload