[40] in java-interest

home help back first fref pref prev next nref lref last post

Re: Strange "new" syntax

daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Wed May 3 19:22:45 1995

Date: Wed, 3 May 1995 14:39:16 -0700
From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
To: java-interest@java.Eng.Sun.COM

Hi Jeremy,

> I came across a piece of syntax for the new operator which (as far
> as I can tell) is completely undocumented in the language spec.

Oops. It should have been mentioned. I'll make sure the language
spec is updated accordingly.

> The syntax is new(string), where "string" appears to be an expression
> evaluating to a String with a class name in it.  Sometimes it's
> used with an expression, but it often just has a constant string.
> 
> So what does it do?  I presume it doesn't call a constructor,
> because no args are passed, or if it does it's the no-arg one.  If
> that's all it does, I don't understand why it's used with a constant
> string.

It creates a new instance of the class named by the string argument.
It can be any expression resulting in a string as long as it
results in a valid public class name. The return type is Object.
So you have to cast it to the type that you need. For example:

	String tagname = "HTML";
	Tag t = (Tag)new("document.tags." + tagname);

You are right that it doesn't make much sense to use a constant
string. Except that it has the advantage that the compiler doesn't
insist that the class exists.

> I suppose as far as compile-time type checking is concerned, the
> new evaluates to something of type Object which you have to cast
> to something that can use.  I got the impression that the runtime
> does all its type checking before actually running the code, but
> I can't see how it can in this case.

The runtime does all the type checking it can at runtime. However,
when you cast an object to a more derived class (narrowing) then
you need to do a runtime check. The VM contains a special bytecode
to do this. It is all totally type safe.

Have fun,

	Arthur van Hoff (avh@eng.sun.com)
	http://java.sun.com/people/avh/
	Sun Microsystems Inc, M/S UPAL02-301,
	100 Hamilton Avenue, Palo Alto CA 94301, USA
	Tel: +1 415 473 7242, Fax: +1 415 473 7104

-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post