Amit,
Class.forName(...) is called reflection in Scala/Java land.  It allows you
to get a class based on a String.  You can then create a new instance of the
class with the newInstance() method.  However, what you get is an instance
of Object... and you have to case it into something else before using it.

In Java, there's only one way to cast things:

Object o = someClass.newInstance();
FooBar fb = (FooBar) o;

In Scala, there are two ways to cast (one is safer and less verbose, the
other is intentionally more verbose):

val a: AnyRef = someClass.newInstance
val fb: FooBar = a.asInstanceOf[FooBar]

or (the radically better way)
a match {
  case fb: FooBar => ...
  case _ => ...
}

Hope this helps.

Thanks,

David


On Mon, Apr 20, 2009 at 4:41 AM, Amit Kumar Verma <cdac.a...@gmail.com>wrote:

>
> Hi All,
>
> This is a sample function for making an object from string at run
> time. Here we are not casting the object but creating one. I wanted
> the same thing for casting the object.
>
> public static Object bindObject(Class className) {
>        Object objOutput = null;
>        try {
>            String sClassName = className.getPackage().getName().concat
> (".Wrap".concat(className.getSimpleName()));
>            objOutput = Class.forName(sClassName.replaceFirst
> ("com.vtech", "com.vtech.appxtension")).newInstance();
>        } catch (Exception e) {
>            try {
>                objOutput = Class.forName(className.getName
> ()).newInstance();
>            } catch (Exception e1) {
>                e1.printStackTrace();
>            }
>        }
>
>        return objOutput;
>    }
>
>
> Thanks to all for kind support..
> Amit Kumar Verma
>
> On Apr 18, 8:51 pm, Timothy Perrett <timo...@getintheloop.eu> wrote:
> > So your talking about reflection right? Take a look at scala Manifests
> > (which aide getting round type erasure) - other than that scala supports
> all
> > the normal reflection tooling that Java does.
> >
> > Tim
> >
> > On 18/04/2009 06:56, "Amit Kumar Verma" <cdac.a...@gmail.com> wrote:
> >
> > > "Scala is a static language, so the class for casting must be known at
> > > compile time.  It's not possible to construct a String at runtime and
> > > cast
> > > an object into a class represented by that String. "
> >
> > > But we use this feature in Java for casting the objects.
>
> >
>


-- 
Lift, the simply functional web framework http://liftweb.net
Beginning Scala http://www.apress.com/book/view/1430219890
Follow me: http://twitter.com/dpp
Git some: http://github.com/dpp

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Lift" group.
To post to this group, send email to liftweb@googlegroups.com
To unsubscribe from this group, send email to 
liftweb+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/liftweb?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to