您当前的课程是:数据结构与算法

 修 改       删 除   设为常见问题   返回列表
发言人:tonni 时间:08月17日 18:38

文章标题:看看New Java Language Features in J2SE 1.5

    Joshua Bloch and Neal Gafter
    Moderator: Edward Ort (MDR-EdO)

    This is a moderated forum.

    
    MDR-EdO: Welcome to Java Live! Our guests today are two key (and well known) members of the Core Java team at Sun -- Joshua Bloch and Neal Gafter. They're here today to answer your questions about the new Java language features in J2SE 1.5 (code name Tiger). So let's begin with a brief rundown -- Josh and Neal, can you give us an overview of the new language features that are coming in J2SE 1.5?

    Neal Gafter: Generics are perhaps the most long-awaited feature. Generics allow you to declare the type of your collections. For example, if before you used a java.util.List to hold Strings, you would always have to cast to String when getting a value out. With generics, you can declare it a List[String] and the compiler can check that it is used in a typesafe way; you don't have to cast when taking values out of the list.

    Josh Bloch: A couple of my favorites are the "enhanced for loop" and "typesafe enums." The enhanced for loop (also known as "foreach") lets you iterate over collections and arrays without using iterators or index variables. Typesafe enums give you all the power of the Typesafe Enum pattern in my book, without all the excess verbosity. There's also a minor feature called static import. It lets you use constants without qualifying them with a class name. Then there's metadata, which lets you avoid boilerplate code in a variety of contexts.

    Neal Gafter: Then there's autoboxing/unboxing and varargs. Boxing allows you to use a primitive int instead of a java.lang.Integer, and unboxing does the reverse. varargs allows you to declare a method that takes a variable number of arguments, which are automatically packed up into an array before being passed to the method.

    Anders: I miss one feature in particular: Tuples.

    Neal Gafter: We did consider tuples. It was one way of handling multiple return types, which was something we considered. Ultimately, we decided the additional expressiveness isn't worth the added language complexity, at least compared to the other things we're doing in Tiger. With generics, you can define your own Pair[T,U] that you can use for much the same purpose. Perhaps we'll consider this in the future.

    dave: Is there any plan to support the const keyword in the future, as in C++? If not, is there a reason?

    Josh Bloch: We do not have plans to add support for the const keyword to the Java language. It was a mixed blessing in C++; as you know, it's merely advisory, and can cast on or off. Gosling hated it, and did final instead. What you really want is "immutable," but it's a research problem to make this work properly.

    wthomp: Does the new typesafe enum pattern support type safety across multiple JVM instances, such as when using RMI, CORBA, and so forth?

    Neal Gafter: Serialization of enums is handled specially so it works between VMs. An enum constant is serialized basically using its type and the name of the enumerator. So as long as the type and enumerator exist in the other VM, you can pass it using RMI and so on.

    zzz: Are you going to introduce something similar to delegates (defined in J++ and C#) in J2SE 1.5 or later (dynamic proxy is not a clean solution)?

    Neal Gafter: No, we don't have any plans for this in Tiger. There are serious semantic problems with trying to add delegates to a language in a consistent way. The main problem is that once you call the delegate, the original class instance is no longer part of the call chain, so overriding in the original class no longer takes precedence over the delegate. It's a hard thing to get right, and I don't think anyone has figured out how to do it in a sensible way yet.

    agomez: Is there a reason to not to support operator overloading ?

    Josh Bloch: Operator overloading is among the most controversial features we've considered. It's nearly essential for numeric programming, but very prone to abuse (as in C++). In particular, it makes it easy to sacrifice the "transparency" that is a Java technology hallmark.

    Annelore: Does the planning for J2SE 1.5 include code converters?

    Neal Gafter: Code converters shouldn't be needed, if you're talking about pre-Tiger Java to post-Tiger Java. The language is upward compatible, and so are the libraries. All your old code should compile and run as it did before. The main exception to this is that enum is now a keyword, so if you're using it as an identifier, you'll have to change it in order to use -source 1.5.

    haddock: What sorts of uses in particular are being planned for metadata? Will C#-style metadata (where you simply declare a function as being a "WebMethod" in order to expose it as a web service) finally make it into the Java language?

    Josh Bloch: Yes, the "WebMethod" functionality will happen! It's not part of the "core" metadata JSR-175, but it is in a follow-on JSR-181. I expect lots of JSRs will have a metadata component from here on out.

    Ezra: Any improvement in performance and memory usage? Any new APIs?

    Josh Bloch: Of course we'll improve performance and memory usage. We're professionals, you know:) As for new APIs, my favorite is java.util.concurrent (JSR-166). It does for concurrency what the Java Collections Framework did for data structures.

    davidelewis: Could you explain the "typesafe" concept in more detail, please?

    Neal Gafter: Well, there are many dimensions to the idea of "typesafe". In the Generics language extension, the compiler inserts casts into your code in the generated bytecode (for example, to String in my previous example). These casts are guaranteed not to fail if the program compiled without any warnings. Warnings can arise because we allow mixing generic code with old non-generic code. If you're trying to generify your code, it is a good idea to try to get these warnings to go away.

    Josh Bloch: The "typesafe" concept is pretty simple. It means that the type system doesn't let you pass in inappropriate values. C enums are not typesafe -- you can say myCar = yourBoat + myFruit; the new enum facility in the Java Programming Language is typesafe; it creates a genuine type for each collection of enums, and you can even add custom methods and fields to the type.

    helbig: Are there any plans to rework java.util.Date?

    Josh Bloch: I wish I could say that we plan to rework Date, but we don't. This is clearly one class that we got wrong; it never should have been mutable. But it's so widely used that it's too late to rework it. Sometimes you just have to live with your mistakes:(

    Neal Gafter: But we are making one small change to Date: it now implements Comparable[Date] instead of just Comparable.

    toniTiger: What's the schedule for Tiger?

    Neal Gafter: I think we're expecting to put out a Beta of Tiger late this year. I don't really remember more than that in any detail.

    dave: Is there any plan to support pass by reference in the future? This includes both primitives and Object references (that is, passing an Object reference *by reference*). If not, is there a reason?

    Neal Gafter: For reference types, they are already passed by reference. If you're wondering about something like out parameters, that's sort of another way of returning multiple values, which as I said we decided not to do in Tiger.

    Jordan: Are there plans to go through the old classes that use static constants and replace them with enums? I know that Swing/AWT uses a lot of these.

    Josh Bloch: We aren't doing this "wholesale," but we're doing it where it makes sense. For example, we're doing some cool work on BigDecimal, and we'll add a typesafe enum for rounding modes as part of that work.

    Neal Gafter: Enums aren't serialized the same way as other classes, so it wouldn't be serial-compatible to just replace them.

    wthomp: To add to Jordan's question, will the improper implementation of constant interfaces, such as with SwingConstants, be replaced in favor of the new constant import mechanism?

    Neal Gafter: Because those constants are now exposed in the APIs, it would not be backward compatible for us to remove them, however horrible they may be. But we hope we can stop people from making that mistake in the future with static import.

    davidelewis: Are elements in an enumeration like structs or simple objects?

    Josh Bloch: Actually, the new enums are more than mere structs. If you want to use them that way, they're full-fledged objects. If you don't add any methods or fields, they're just "rich" typesafe enum constants. By "rich" I mean that they support all sorts of useful basic functionality, such as printing, comparison, serialization, and the like.

    Annelore: What about default parameter values for constructors?

    Josh Bloch: I don't think we'll ever add support for default parameter values for constructors or methods. Overloading provides similar functionality, and we don't like having many ways of doing the same thing.

    Tim Peierls: How close would you say the 2.2 early access compiler is to the final Tiger release, with regard to JSR-14 features only?

    Neal Gafter: The 2_2 early access compiler is pretty close to the way the language features will appear. For those who don't know, there is an early access compiler that you can use to try out the new language features (except metadata). There are still some minor changes in the works; for example, the 2_2 prototype is missing some required warnings on some casts, and we know the diagnostics need to be improved, and we're supposed to allow array of Whatever[?], which isn't currently allowed.

    Paulo Mattos: Besides the Collections Framework, which other J2SE classes will be refactored to incorporate the generics facility? I can see some good candidates, like: java.lang.ThreadLocal, java.lang.ref.Reference, java.util.EventObject (getSource() method), and so forth.

    Josh Bloch: Good guess! All of the "wrapper" classes like weak references and thread locals will be retrofitted to use generics. So will some APIs that return specified generics (for example, List[String]).

    Neal Gafter: We're also generifying class Class, so X.class is of type Class[X]. This is fairly important, but the explanation is a bit involved.

    Matt DeVore: Did you consider support for attributes in 1.5?

    Josh Bloch: We are supporting this functionality. We call it Metadata, or "Program Annotation." It's the subject of JSR-175.

    JFarre: What about supporting "references to references"? I know it's one of the hardest things to learn in C, but it allows us to almost do magic...

    Neal Gafter: This is sometimes called "hooks", and I do miss this ability in the Java language. The closest thing we have is java.lang.Ref. We haven't considered adding anything like pointers-to-pointers in the Java language.

    pholser: I've been exploring .NET/C# over the past few months. I really like its metadata feature, in the form of attributes with which one can annotate classes/methods/fields, that other tools can inspect at runtime. NUnit, for example, uses [Test] and [TestFixture] attributes to build and execute test suites, as opposed to JUnit's idiom of extending class TestCase and naming test methods via convention (public void testXYZ()). How does JSR-175's metadata capabilities compare with those of .NET?

    Josh Bloch: The short answer is "yes." Our metadata facility will support all of this. I happen to think ours is a bit cleaner, but you be the judge. The proposal should be released for public review shortly.

    Laurence Vanhels: From profiling sessions, it's clear that any Java program produces a huge number of String objects. Does the new release include any new clever optimizations to speed up the general use of Strings?

    Neal Gafter: Yes! String concatenation is fairly slow right now because StringBuffer is fully synchronized. We're adding an unsynchronized version, java.lang.StringBuilder, with the same functionality but not synchronized. It will be used by the compiler to compile string concatenation expressions, and this should significantly improve performance for some applications.

    ParthaPal: If typesafe enums are classes, how would we examine those using reflection?

    Josh Bloch: The reflection APIs are indeed being extended to handle enums, and generics and annotations as well:)

    ph: What about a priority queue class with constant read access?

    Neal Gafter: I think you mean log(n) access; it's hard to do better. Yes, such a thing will be included as part of JSR-166.

    pholser: In your opinion, what will be the biggest cognitive hurdles for C++ programmers to clear when attempting to grasp Java generics?

    Neal Gafter: C++ templates are like macro expansion; Java generics can't be specialized. You can't use an int as a generic parameter. Java generics are more fully integrated into the language's type system.

    Paulo Mattos: Will java.util.logging.Level be refactored as an enum in J2SE 1.5 ? If not, why not?

    Josh Bloch: Sorry to say I don't know the answer to this one. I believe that Calvin Austin is in charge of those APIs these days. I suspect that we won't be doing that in Tiger, but maybe later.

    dave: Some of the documentation I've read on generics suggested that one cannot make method calls on a generic type; that is, you can't execute this: [T] method(T t) {t.methodOfT();}, because the compiler will not statically check all instantiations of T, to ensure that they have a method called methodOfT(), as is done with C++ templates. Is this accurate? It seems, then, that the primary use of generics is to enable static type-checking, but not generic method calls.

    Neal Gafter: Java generics are strongly typed, so you can only call a method that is a member of the \bound/ of the type parameter. So, for example, you could define a generic method [T extends Foo] void f(T t) { t.whatever(); }, and this will constrain the type parameter to be some subclass or subinterface of Foo. If Foo has a method whatever(), this will be allowed, and is statically typechecked and typesafe.

    Laurence Vanhels: Any plans to implement a JVM initialization approach that pre-loads the bulk of "always needed" classes as one big binary image, thus avoiding the performance hit of having to go through the painfully slow "manual" class loading/linking of those classes?

    Josh Bloch: We've been doing research in this area for quite some time. It turns out that it's easier to do more harm than good. When it's a performance win, we'll release it.

    rrhodes: Will metadata introduce a new language keyword, or will it use comments like javadoc?

    Josh Bloch: The short answer is "neither." It makes clever use of existing "punctuation." To declare an annotation type: public @interface Foo { ... } Here "@interface" means "annotation-type" (get it? a-t -] at -] @) Also, it looks like a javadoc tag, which is a form of metadata. To annotate: @Copyright("Acme Inc") public static final int baz(...) { ...} For all of our new features, we've tried hard to avoid new keywords, but to keep the syntax pretty. The only new keyword we're adding is enum.

    JFarre: Will generics support native types? If not, why not?

    Neal Gafter: The short answer is "no," but if you instantiate a generic using Integer, boxing/unboxing will allow you to use it with primitives. The reason is that a generic is not macro expanded, but generates a single class file.

    JFarre: Smalltalk uses nontyped variables that can hold objects of any class, and let you invoke any method of that class. It also reduces the impact of making changes to some classes in a big application. Could you give reasons why it's better to do it as in the Java language?

    Neal Gafter: This is an ongoing debate in the programming language community: do you have static typing and more typechecking at compile time, or more flexibility and defer errors to runtime? We prefer to have our spacecraft software fail at compile time rather than in space. But in the Java language, you can always use Object.

    dave: Will Tiger allow multiple bounds on generics? If I need objects to have methods m1() and m2(), where the methods come from different interfaces, can I do this?: [T extends Interface1, Interface2] void f(T t) { t.m1(); t.m2(); }

    Josh Bloch: Yep, you can do it.

    Neal Gafter: The syntax for multiple bounds is: [T extends Interface1 & Interface2]. We use & instead of , (comma) because , (comma) is used to separate different type parameters.

    davidelewis With generics and native types, would it be possible to pass a native int into the following method?: void doInt (Integer myInt)

    Josh Bloch: You can do this, but what you're really doing is autoboxing; the compiler uses a static factory to pass the int as an Integer.

    Paulo: Any plans to incorporate a reverse-order "foreach" facility? Maybe for java.util.List and arrays only?

    Neal Gafter: There is no iterator type defined that is intended to have reverse semantics. However, you can easily do that with the existing facility; it all depends on how you elect to implement your iterator.

    Manu: What about JSR-175 and metadata? The JSR is still in "opaque" mode. Could you provide "early access" info?

    Josh Bloch: Sorry it's taken us so long to get you a spec. I'm the JSR-175 spec lead, so I guess you can blame me. We'll have it out soon. I expect it will be in Community Review next week, and in Public Review in about a month. We "leaked" a bit of information in a BOF at JavaOne, and I'll be happy to send you the slides to the BOF. Of course they're already out of date:)

    Neal Gafter: Also, I hope to have an early access that includes JSR-175 support by around mid-September, possibly earlier.

    ParthaPal: Any new features to prevent thread deadlock in 1.5?

    Josh Bloch: Arguably, JSR-166 (java.util.concurrent) is such a feature. People tend to get deadlocks when they're rolling their own thread utilities (like work queues, thread pools, and the like). You won't have to write your own anymore:)

    toniTiger: I had heard that J2SE 1.5 will have some additional support for printf? Is that true? Can you tell me what support will be added?

    Neal Gafter: There will be new I/O libraries that look a bit like C's printf. This is only possible now because of varargs and autoboxing.

    agomez: Will a mechanism be added to query about an enum element and its predecessor and successor? (in other words, +1, ++, Enum.element.predecessor)

    Josh Bloch: We may or may not provide that functionality; the expert group will be discussing this in the next week or so. It certainly is possible to "roll your own," since we provide access to the entire universe of enum constants for an enum type, in (unmodifiable) List form.

    Matt DeVore: Is there support for attributes for accessing member data as an alternative to get_ and set_ accessors?

    Neal Gafter: Yes! When you define an annotation type, you're really defining an interface that will be used to access the elements of the annotation. It looks something like this: public @interface Author { String value(); }. This defines an annotation type that is used like this: @Author("fluffy bunny") void f() {}. When you're accessing the annotation, you actually use the Author interface to read the values.

    Tim Peierls: Any hope for a javadoc that is aware of the language features as part of an early access release?

    Neal Gafter: We're sorry, this has been too long in coming. Yes, we really hope to get a javadoc into one of the early access prototypes, but unfortunately there are a number of people involved and all the pieces have to be there (javadoc tool, new API, new doclet, and so forth). I'm hoping for mid-September, around the time of JSR-175 in the prototype.

    wthomp: Is there a new Sun Certification test in the works that will incorporate new 1.5 features/keywords?

    Josh Bloch: I would assume the answer is yes. Of course they can't write the test until we finish the language features:)

    Yoseph: For multiple bounds, was there a reason why the [Type1 extends Interface1 & Interface2, Type2] was chosen over the [Type1 implements Interface1, Interface2; Type2] syntax?

    Neal Gafter: The main reason we even use [] brackets is for C++ programmers. It's really a judgment call. Some people prefer one syntax and some the other. Your suggestion isn't unreasonable, but we just had to pick something. Multiple bounds are rare enough that the common case of multiple type parameters should be more comfortable.

    Yoseph: I like the use of [ and ] for multiple bounds. My problem is with the use of &, and extends (instead of the implements or extends) along with ; (semicolon) to divide between types.

    Neal Gafter: You can't satisfy all the people all the time.

    Manu: Metadata could be associated with objects for many goals. Generic: the provided information will impact most uses of the object. (cardinality,...). Specific: this kind of info is only relevant to specific usage of the object. (column and table names ...). Are you going to provide a solution to this problem -- avoiding mixing specific and generic metadata? (Look to J2EE for such a mix ....)

    Josh Bloch: I'm not quite sure what you mean, but I think the key point is that the Program Annotation (AKA Metadata) facility is totally general. We're counting on the designers of annotation types to use the facility tastefully, and I'm sure they won't disappoint.

    dynamite: Is virtual machine sharing going to make it into Tiger?

    Neal Gafter: Unfortunately, no, because of schedule constraints. Even if it were included, it would be a trivial implementation that doesn't actually share, but rather forks off a new VM per isolate.

    hkratz: Will other parts of the JDK API (for example, Swing) be retrofitted to make use of generic types?

    Josh Bloch: As I mentioned before, we're doing a bit of this. As for Swing, I don't know. Sorry to say, that team doesn't even use Collections yet. On the other hand, perhaps generics will give the Swing engineers the motivation to do all of this work in one fell swoop:)

    wthomp: Will the new features of Tiger be utilized on a spacecraft in the near future? If so, where might I find more information about that project?

    Neal Gafter: I don't know. I hope so. The Mars rover is using J2ME. I expect a very long lead time before NASA would consider a technology suitable for use in space, so I would expect a few years before Tiger is running in space. If the language weren't typesafe, perhaps it would be longer.

    toniTiger: Is there any way I can use these new features sooner than the end of the year?

    Neal Gafter: You can download the prototype. It includes support for most of the new language features, and will be updated as we complete things. It even includes full sources for the compiler.

    dtbullock: Is JSR-75 considering metadata for packages -- for example, a package spec and implementation version.

    Josh Bloch: I'm happy to say that the answer is yes. It's quite pretty. You can replace package.html with package.java, and put the package annotation in there, along with the package javadoc.

    dtbullock: Very nice! Thanks for thinking that one through. Having package metadata will be a boon at develop, build, and runtime.

    Josh Bloch: Thanks a lot for the feedback. I'll tell the expert group, who will be thrilled.

    agomez: When will you start working on version 1.6 ?? ;)

    Neal Gafter: We're working on 1.6 now, just as we were working on 1.5 (for example generics) way back when we did 1.3.

    haddock: How confident are you that these new features will make any major contribution to the Java language any time soon? Logging, NIO, and some other features in JDK 1.4 certainly haven't really permeated very many projects.

    Josh Bloch: I'm quite confident that these features will make an immediate contribution when people start using 1.5. They're quite compelling. They let you get your work done faster and with fewer bugs. I've used them, and they're addictive:)

    Yoseph: I didn't get a chance yet to look at the 2.2 prototype properly, but it was my understanding that a draft spec for the varargs syntax would be included in it. I think I now see what is trying to be done with James Gosling's Object... syntax. Is the autoboxing way of doing varargs also allowed? And what does the Object... syntax give us that the autoboxing didn't?

    Neal Gafter: Autoboxing only applies to primitive types; it doesn't give you varargs at all. Varargs saves you from having to type new Object[] { and the } (curly brace) at the end.

    haddock: Have groups in other parts of the Java world (J2EE, J2ME), voiced their intention to use metadata in any significant way? Any examples you'd care to share?

    Josh Bloch: There's something fishy about that question. No, only kidding... The short answer is yes. Several JSRs should make use of metadata, generally in the J2EE/web services sphere. For example, see JSR-181.

    Neal Gafter: I would like to use metadata to write a parser generator. The grammar rules would be embedded in the code as annotations. With this now possible, there is no need to define a new separate "parser language" as is necessary for yacc and so forth.

    helbig: Will there be a third edition of the Java Language Specification?

    Neal Gafter: Yes. We hope to have drafts circulating, at least internally, around December. Hopefully a published version will be available by JavaOne 2004.

    Josh Bloch: Hi Mom!

    haddock: He! He! Does Java run in the family, Josh? :)

    Neal Gafter: Yes, it runs in his family, but only in Interpreted mode.

    Josh Bloch: Mr. Fish -- it certainly does. My wife is the coauthor of the J2ME style guide:)

    Neal Gafter: If you have more questions about language features, you can send them to the comments alias for the relevant JSRs (14, 175, 201). There is also a generics forum that I visit frequently. There's also a comments email alias in the prototype.

    MDR-EdO: Well, we've come to the end of today's session. I want to thank everyone for participating today. I thought we had an excellent range of questions, And of course I'd like to thank our guests Josh and Neal for their answers. Look for a transcript of today's session to be posted on java.sun.com in a day or two.

    Neal Gafter: This was fun!

    wthomp: Thanks for your time guys, and keep up the great work!

    Neal Gafter: Thanks. Do try the prototype!

    Josh Bloch: Well, that went fast. Thanks everyone. I had fun chatting, and I encourage you all to download the early access prototype and play with it. It's a blast. Just like the Java programming language -- only better:)

    Neal Gafter: Don't program like my brother!

    



 回复文章:
 我要回复
标 题:
关键字:
内 容:
相关文件:  
文件说明: