Inject a class from a passed in string of fully qualified classname.

45 views
Skip to first unread message

hambone

unread,
Apr 11, 2012, 9:34:40 AM4/11/12
to google...@googlegroups.com
I am writing an API and I want the client to be able to pass in a fully qualified class as a param.

UseApi api = new UseApi("com.company.classes.thisClass");
api.process();


Can I use Guice to take a fully qualified class string and inject the class in the code that implements process() as an example. In my code I want to be able to say

public class UseApi {
   public final String clazz;

  public UseApi ( String clazz ) {
    this.clazz = clazz;
  }
  public void process()
  {
     // inject an instance of com.company.classes.thisClass
    Object theirClass = inject this.clazz
    theirClass.someMethod();
  {
}

This assumes I also have access to the compiled passed in class.

Thank you so much in advance

Marko Lavikainen

unread,
Apr 13, 2012, 4:48:06 AM4/13/12
to google...@googlegroups.com
Can't you use Class.forName("classname") to get injectable class?

Christian Edward Gruber

unread,
Apr 13, 2012, 1:18:22 PM4/13/12
to google...@googlegroups.com
You should be able to do this, so long as you're not playing crazy games with classloaders. Class.forName() is not advisable, as you don't always get the right classloader. But in principle this can work.

Christian.

On Apr 13, 2012, at 4:48 AM, Marko Lavikainen wrote:

> Can't you use Class.forName("classname") to get injectable class?
>

> --
> You received this message because you are subscribed to the Google Groups "google-guice" group.
> To view this discussion on the web visit https://groups.google.com/d/msg/google-guice/-/vobIgFUrxPYJ.
> To post to this group, send email to google...@googlegroups.com.
> To unsubscribe from this group, send email to google-guice...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
>

Reply all
Reply to author
Forward
0 new messages