Reflection of a implemented interface

H

homecurr

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
 
C

Chris Smith

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,737
Latest member
Georgeengab

Latest Threads

Top