Re: When will reflections support casting (especially for constructors, etc) properly?



brian.vanheesch@xxxxxxxxx wrote:
Consider the following code:

class A
{
}

class B extends A
{
}

class C
{
   public void foobar(A a)
   {
   }
}

...

Object b=Class.forName("B").newInstance();

Class clazzA=Class.forName("A");
Class clazzC=Class.forName("C");
Object c=clazz.newInstance();

Method m=clazzC.getMethod("foobar", clazzA);
m.invoke(c, b);

This will result in an exception, since b is not of type A (the extend
is not considered).  Anyway around this?  Clearly typecasting will do,
but can't figure out how to typecast using reflection if you only have
the class string "A" as a reference of the target typecast class.

You should try running this before posting... it doesn't compile. Even once I got it to compile, it doesn't result in an exception for me.

Also the private/public/protected modifier for the method (doSomething,
in this example) MUST be public (even if reflection code lives within
the class C), any around this?

I suspect you mean "foobar" and not "doSomething", but I don't see why you would want it any other way. The idea of private method is such that objects not of the same class cannot access those methods.
.




Relevant Pages

  • Re: constructor problem
    ... > compile because it's riddled with syntax errors. ... /*This is the tester class for testing the specialAccount2 object ... private String customerName; ... public void setAmountOwing{ ...
    (comp.lang.java.help)
  • Re: Thread doesnt interrupt!? HELP please
    ... I took a boolean "stopUpdate" as nos proposed to do. ... "isUpdating" to false. ... public class MyClass extends JFrame{ ... public void updateThumbs() { ...
    (comp.lang.java.programmer)
  • Re: WebService Problem
    ... > I am creating webservice DocManager to store documents.I have a method ... > where path is path of file on server and stream is stream of document. ... compile the client it gives compile time error ... > public void Uploadfile ...
    (microsoft.public.dotnet.framework.aspnet.webservices)
  • Re: instanceof NOT (always) bad? The instanceof myth.
    ... It has been said that, in most cases, instanceof should not be used to ... if (other instanceof Foo) { ... public void move; ... scare; // does not compile ...
    (comp.lang.java.programmer)
  • Re: Compiler bug? "reference to addAll is ambiguous"
    ... extends E>) in java.util.List<capture#420 ... super gov.sc.eip.report.birt.items.ChangeRow> match ... I assume E extends ChangeRow. ... public void addAll(Collection<? ...
    (comp.lang.java.programmer)