Main is varargsable
It's cute, although I admit there isn't much utility in it: public class Hello { public static void main(String... args) { System.out.println("yippee!"); } }…
It's cute, although I admit there isn't much utility in it: public class Hello { public static void main(String... args) { System.out.println("yippee!"); } }…
Challenge: can you write code that invokes foo()? class Impossible { public Impossible() { throw new AssertionError("you cannot instantiate me"); } public void foo() { System.out.println("The impossible is possible!"); } } The solution is in the comments...…
Laurence Gonsalves prefers compile-time code generation over runtime reflection. He writes, I think all-in-one toolchains (eg: IDEs) are actually part of the reason Java has both not enough magic (like Rob says) and also the wrong kind of magic (runtime reflection). If there was a standard way to plug code…
Java's type system isn't expressive enough to model everything exactly. But it's expressive enough to be productive! Our type-unsafety-is-okay precedent is Collection.clear(), JJB's infamous optional method. Type safety advocates see @throws UnsupportedOperationException and claim that it's damning of either the collections framework or the type system. But I claim…
I'm about a year late for project coin. But I still want an obvious Java language feature: !instanceof. To illustrate: public void equals(Object other) { if (other !instanceof Foo) { return false; } return ((Foo) other).bar.equals(bar); } With the instanceof operator, null instanceof T is false for all values of…
Out of the box, Windows computers work with whichever accessories you buy for them. If you get an MP3 player, it doesn't matter who sells it. Walkman, Zune and Sandisk devices all sync with Windows Media Player. But Macs can't do this. Connect a GoGear to a MacBook and you'll…
I've been working on bringing Android's DOM implementation up to version 3. This process has exposed me to some ugly code. For your entertainment, here are the worst bits: DocumentBuilder.parse() doesn't accept references to unparsed entities. But you can build such a DOM programatically. The API doesn't specify whether…
Java's Integer class includes two methods for converting values into Strings. There's a general one: /** * Converts the specified integer into a string * representation based on the specified radix. */ public static String toString(int i, int radix) { ... } Plus there's also methods for commonly used bases: /** * Converts the specified integer into its…
In working through some bugs in Harmony, one thing that's been consistent is my surprise. Floating point's special values slightly complicate things... Negative Zero Floats and doubles have two distinct representations for nada: 0.0F and -0.0F. NaN Rather than risking an ArithmeticException, floats model error values natively. There…
John Gruber praises the iPhone's lack of upgradeable storage: I simply don’t understand why Motorola doesn’t follow Apple’s lead and provide ample built-in storage rather than relying on removable SD cards. He overlooks an obvious benefit of having SD cards for storage: they're cheaper! Compare what it…
Suppose you've got a string that contains a floating point number: "3.5" or "2.5E-3". Your goal is to get a float from that number. There are a few different techniques to try... If you're familiar with parseDouble(), you could use that and then cast:…
I absolutely love IntelliJ IDEA; it's my favourite application. This tool makes programming in Java fun. It's my gateway to the zone, that magical hypnotic place where I disappear into the code for hours at a time. I write better code because I use IntelliJ, and I enjoy my job…
I just uploaded a new Android app, Shush! Ringer Restorer: When you turn your ringer off for a movie, this app turns it back on afterwards. It's activated when you silence your ringer using the volume buttons. You don't need to remember a special app! Once your ringer is off,…
Joe Clark, author of a fantastic book on Canadian English and a childish rant about Google employees is at it again. This time he's planning a book about how copyright benefits creative people: Who’s sticking up for the individual creator? Neither side is. The maximalist side wants to collect…
Part 3 in a Series. Background: modelling configuration One of the most distinct features of Guice is our fluent embedded domain specific language (DSL). By chaining method calls, Guice supports a wide combination of binding sources, targets and scopes: bind(PaymentService.class) .annotatedWith(Names.named("creditCard")) .to(VisaPaymentService.…
Part 2 in a Series. Background: marking nulls Null is bad. Most of the time, use of null indicates clumsy modeling. Instead of null collections, use empty ones. Instead of a null service, use a no-op implementation. The JDK gets this wrong for comparators by using null as a stand-in…
To celebrate the release of Guice 2.0, I'd like to showcase my favourite parts of the new code. In this N-part series, I'll go deep into the implementation details to explain the clever and interesting code within the project. I'll focus on general techniques that you can use in…
Back in February, a discussion flared up over Guice's lack of support for industry-standard annotations. James Strachan described the problem succinctly: So my show stopper issue with ever adopting & recommending Guice is to be able to use IoC framework agnostic annotations for lifecycle & injection (JSR 250/EJB3 for…
Pop Quiz The following is a method from a very decent implementation of Java SE. I've substituted x and y for the actual method name and parameter type. What are the values of x and y ? public static boolean x(y z)isNaN(float z) { return z != z; } PS -…
JavaOne is coming up, and now is the time to convince your boss to send you. You only need to learn a few productive tools for the conference to pay for itself. In addition to the Guice talk, here's some sessions I'm excited about... Developing LimeWire: Swing for the Masses…
FileCharSequence adapts a java.io.File as a CharSequence which has nice consequences. For example, you can run Java regular expressions directly against a File. And you can easily send part or all of a file to a StringBuilder or Writer: /** * Adapts a text file as a character sequence so…
Dhanji and I are doing some Guice talks over the next two months. First, we'll be presenting at Google I/O. This conference is fast, web-focused, and cutting edge. It's also affordable: $300 if you register before May 1. Big Modular Java with Guice Learn how Google uses the fast,…
I love listening to The Java Posse. Back when they mentioned Glazed Lists on episode 76, I was majorly psyched. I ran home and played the relevant clip for my wife, who's usually annoyed at the amount of time I spend programming, "See Jodie? See, see? I feel so…
Internet addresses are no longer stuck with ASCII and English. If you're Greek, you can have a Greek domain name; if you're Japanese you can have a Japanese domain name. To make international characters work on the existing ASCII system, you encode the address in Punycode: As an example of…
In the rare situation that you need to preprocess .java files, Munge is a pretty decent tool for getting it done. From Tom Ball's blog, So a combination preprocessor and string translator, Munge, was created to address [supporting Java 1.1 and Java 2] (source). Since its requirements were that…
jarjar is a sweet Java packaging tool that allows you to embed one .jar file in another. But rather than just smashing the jars together in one big archive, jarjar renames the embedded .jar's classes so that they live in the main jar's namespace. For example, Guice's ProxyFactory.java file…
Inspired by the URL-as-question meme sites http://has the large hadron collider destroyed the world yet.com and http://should I use tables for layout.com, I present http://how many spaces after a period.com:…
I love my new G1, but it doesn't work with Audible yet. Fortunately, I have a workaround. This guide describes how to get audiobooks onto a G1. You'll need a Mac and $40 worth of software. Download and install Tune4Mac. This app creates a virtual CD burner on your Mac,…
Java 5 Type Erasure is frustrating. I'm coding along, enjoying the glorious type safety of generics. And then I try to do a little more with the Ts, and erasure shows up, "You can't do that!" I can't test an object if it really is a T. I can't inspect…
Dependency injection is addictive. The pattern allows our applications to grow without harming developer productivity. But we have seen technical hurdles... Sometimes our modules have competing dependencies. For example, we have a BillingModule and a PermissionsModule, each of which has a private database. If we configure two PersistenceModules to talk…
I never learned sed or awk. Or even Perl. But I'm pretty good with Java's regex, and I'm familiar with the new text formatting facilities in Java 5. So rather than tricking myself into learning sed and awk, I wrote my own stream processor that uses Java's regex and pattern…
Part 17 in a Series. I really like the Java Collections API. So much so, that I use 'em when I'm doing work that isn't particularly collectioney. For example, I recently wrote a quick-n-dirty app that rewrote some files line-by-line. Instead of using a Reader as input, I used an…
Part 16 in a Series. The traditional approach to unions is to first create a new Set, and then to addAll using each component set. You can use a similar approach to do differences and intersections. Before: private static final ImmutableSet<String> LEGAL_PARAMETERS; static { Set&…
The Google Tech Users Group is hosting a talk that will interest Java developers: Overview: How the Google Collections Library builds on java.util to provide more building blocks for doing your job. Where: Building 42 of the Googleplex, Mountain View, California When: 6:00pm Food, social, demos and announcements…
I do this really annoying thing when I'm hanging out with my wife. I correct her when she uses the "wrong" words... We're walking around town when we see something out of the ordinary - like a humongous fat dog or a friendly hobo or a police chase.…
Today I did something I've never done before - I created a method that's an 'alias' to another method. I still think this is the right thing to do, but I still find it kind of weird... Getting Providers Binder.getProvider() allows your module to get a Provider<…
Nobody reads imports. Good IDEs do their best to pretend imports don't even exist - they'll hide 'em from you, and manage them for you. They'll even add imports on demand when you're writing new code. Suppose you create your own, say @Inject or @RequestScoped annotation. In the code, it's…
It's diminishingly rare that I get to write code that improves the internals of both Glazed Lists and Guice... Glazed Lists' BeanProperty BeanProperty is a convenient utility class that can expose a JavaBeans getter/setter property as its own object. You give it a class (like Baz.class) and a…
It's really tempting. As far as devices go, iPhone 3G is the best there is. It's a generation ahead of its competitors, and the gap is growing. The app store is great for both developers and for its users. But I'm not gonna get one: **Amazon MP3. ** Lots of good…
Suppose it's the early 1990's and you're James Gosling implementing String.substring(int, int) for the first time. What should happen when the index arguments are out-of-range? Should these tests pass? Or throw? public void testSubstring() { assertEquals("class", "superclass".substring(5, 32)); assertEquals("super"…
Our application has two implementations for one interface. EnergySource is implemented by both Plutonium and LightningBolt: class DeLorean { @Inject TimeCircuits timeCircuits; @Inject FluxCapacitor fluxCapacitor; @Inject EnergySource energySource; } interface FluxCapacitor { boolean isFluxing(); } @Singleton class RealFluxCapacitor implements FluxCapacitor { @Inject TimeCircuits timeCircuits; boolean isFluxing; public boolean isFluxing() { return isFluxing; } } class TimeCircuits { Date whereYouveBeen;…
One of the nice new features of Guice 2.0 is the new introspection API. It's the equivalent of java.lang.reflect for Guice - it lets you inspect your application at runtime. Our goal is to make it easy to write rich tools for Guice. A natural use case…
Shortly after fixing arrays, I've found another multiple representations bug. This problem is probably familiar - I'm confusing primitive types (like int) with wrapper types (like Integer). It's one binding The critical question: should these tests pass? assertEquals(Key.get(int.class), Key.get(Integer.class)); assertEquals(TypeLiteral.get(int.…
I'm feverishly preparing Guice for the 2.0 release later this summer, and tonight I scanned through our issues list. There's a whole bunch of good features that I won't get to before our release. So I'm looking for Guice users to help out with development! Introducing javax.interceptor javax.…
There's a class of bugs that come up when one logical datatypes has representations in multiple classes. The best example of this is 1 vs. 1L. Both ones represent the same data. But new Integer(1) is not equal to new Long(1) according to the corresponding equals() methods. Calling…
Bob and I are giving a talk at Google's developer conference tomorrow. From the session summary: Wed 11:15am - 12:15pm Bob Lee, Jesse Wilson Guice (pronounced 'juice') is a Jolt award-winnning, lightweight dependency injection framework for Java 5 and above. Put simply, Guice alleviates the need for factories…
Kasper complains that it's hard to call methods that always throw. In particular, code like this won't compile because findGetter is missing a return statement: public Method findGetter() throws CsvException { try { return type.getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)); } catch(SecurityException e) { noSuchGetter(e)…
In our functional tests, we prefer to launch an application that closely resembles the production one. This means using the production modules in a proper staging environment. Even with automating scripts, setting up the environment is time consuming and tedious - it requires database install and configuration, permissions, SSL certificates,…
Building out the Multibindings extension, David P. Baker has written a new class that simplifies Map binding. MapBinder uses an API that's consistent with Multibinder: public class SnacksModule extends AbstractModule { protected void configure() { MapBinder<String, Snack> mapBinder = MapBinder.newMapBinder(binder(), String.class, Snack.class); mapBinder.addBinding(…
In the first and second parts of this series, I discussed hooks for extending Guice. In this post I introduce private bindings. Don't emulate Guice The key to a good extension is tight integration with Guice. In particular, the extension shouldn't copy functionality from Guice; doing so can lead to…