Reflection of a implemented interface

Discussion in 'Java' started by homecurr@yahoo.com, May 20, 2004.

  1. Guest

    public interface IA{...}
    public class A implements IA{...}
    public class F{
    public F(IA ia){...}
    }

    If I do this:

    A a = new A();
    F f = new F(a);

    It works fine. But if I do this:

    A a = new A();
    Class clazz = Class.forName("F");
    Constructor constructor = clazz.getConstructor(new Class[]{a.getClass()});

    The last line does not work because F does not have a constructor like F(A){}.
    Why? How can I fix it? I have to use the reflection in my project.

    Thanks,

    John
    , May 20, 2004
    #1
    1. Advertising

  2. Chris Smith Guest

    wrote:
    > public interface IA{...}
    > public class A implements IA{...}
    > public class F{
    > public F(IA ia){...}
    > }


    [...]

    > Class clazz = Class.forName("F");
    > Constructor constructor = clazz.getConstructor(new Class[]{a.getClass()});
    >
    > The last line does not work because F does not have a constructor like F(A){}.
    > Why? How can I fix it? I have to use the reflection in my project.


    Since you no longer have the compiler to help you at runtime, you'll
    need to resolve the desired constructor on your own. That means walking
    through the superclasses and superinterfaces of the class in question,
    looking for a constructor that works.

    Just as is the case with the compiler, it's possible to find an
    ambiguous match (for example, two unrelated superinterfaces both match).
    The compiler will give an error at compile-time in this case; you need
    to decide how to deal with it at runtime.

    --
    www.designacourse.com
    The Easiest Way to Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
    Chris Smith, May 20, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Raffael Vogler
    Replies:
    2
    Views:
    342
    Raffael Vogler
    Dec 18, 2003
  2. Replies:
    2
    Views:
    374
    Michiel Konstapel
    Dec 11, 2004
  3. Replies:
    2
    Views:
    378
    Alun Harford
    Feb 8, 2006
  4. Nathan Sokalski
    Replies:
    1
    Views:
    506
    RobinS
    Nov 21, 2006
  5. Lew
    Replies:
    11
    Views:
    559
    Lasse Reichstein Nielsen
    Sep 8, 2008
Loading...

Share This Page