bind from a class name

253 views
Skip to first unread message

Bill de hOra

unread,
Mar 24, 2010, 10:04:56 PM3/24/10
to google...@googlegroups.com
Is there a way to bind from a class name (ie the class' string name)
instead of a .class?

Bill

Bob Lee

unread,
Mar 24, 2010, 10:25:05 PM3/24/10
to google...@googlegroups.com
Can you give an example of what you're looking for?

Thanks,
Bob

Dhanji R. Prasanna

unread,
Mar 24, 2010, 10:53:11 PM3/24/10
to google...@googlegroups.com
Can't you use Class.forName in between?

On Thu, Mar 25, 2010 at 1:04 PM, Bill de hOra <bi...@dehora.net> wrote:
Is there a way to bind from a class name (ie the class' string name) instead of a .class?

Bill


--
You received this message because you are subscribed to the Google Groups "google-guice" group.
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.


Bill de hOra

unread,
Mar 29, 2010, 4:31:14 PM3/29/10
to google...@googlegroups.com
It's to be able to wire in an implementation from a simple plugin
descriptor, ie from a text/xml file rather than code.

I tried Dhanji's idea - Class.forName returns Class<?>, which can be
cast to the interface, eg,


try {
Class<?> aClass =
Class.forName("presence.service.MemoryPresenceService");
PresenceService o = (PresenceService)aClass.newInstance();
bind(PresenceService.class).to(o.getClass());
} catch (Exception e) {
....
}

the downside isn't so much a cast as having to have '(PresenceService)'
in the code itself.

I suppose I could go OSGi, but that's a big meal to eat. I'm wondering
if scanning for module classes annotated with @Plugin or something
wouldn't be better, ie ask plugin providers to ship a guice module
instead of using text config.

Bill

Dan Godfrey

unread,
Mar 30, 2010, 8:52:20 AM3/30/10
to google-guice
If you're on Java6 and can put the text file on the classpath, you
could have the ServiceLoader instead of annotating and then scanning
for @Plugin.

http://java.sun.com/javase/6/docs/api/java/util/ServiceLoader.html

Yegor

unread,
Mar 30, 2010, 10:20:23 AM3/30/10
to google-guice
>    PresenceService o = (PresenceService)aClass.newInstance();
>    bind(PresenceService.class).to(o.getClass());

Variable o seems unnecessary, as it is only used to get the class of
MemoryPresenceService, which you already have in variable aClass.
Instantiating the class unnecessarily may lead to bugs/performance
issues. I recommend doing this instead:

try {
  Class<PresenceService> aClass = (Class<PresenceService>)
Class.forName("presence.service.MemoryPresenceService");
  bind(PresenceService.class).to(aClass);
} catch (Exception e) {
....
}

Reply all
Reply to author
Forward
0 new messages