Wednesday, March 10, 2010

Instantiate java classes, assign to variables

The goal is to read from a URL and print the returned html, much like this Java code:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class URLReader {
private static void getURL() throws IOException {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(yahoo
.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();
}
public static void main(String[] args) throws Exception {
getURL();
}
}



So there is some figuring out to do. We need to import some classes, instantiate them, call methods on the object instances, etc. Here, we are trying to learn this one step at a time.

In a future post, we will learn how to put all these together and print the returned html. I say "future" post because I don't know how to do this simple task. I guess it requires a new way of thinking compared to imperative languages like Java. And I don't find this easy at all - how to loop, which functions to use in which context, etc. - thinking in terms of function chains. But we will persist ... and learn. :)

Anyway. What follows are some of the individual commands.

We first go to the clojure prompt by entering this command in a DOS window

C:\clojure-1.1.0>java -cp clojure.jar clojure.main
Clojure 1.1.0
user=>

; import a Java class, java.net.URL in this case
user=> (import java.net.URL)
java.net.URL

; create a new URL object
user=> (new URL "http://www.yahoo.com")
#

; create a new URL object and invoke its getHost() method
; In Java: new java.net.URL("http://www.yahoo.com").getHost()
user=> (. (new URL "http://www.yahoo.com") getHost)
"www.yahoo.com"

; create a new URL object and invoke its openStream() method
; In Java: new java.net.URL("http://www.yahoo.com").openStream()
user=> (. (new URL "http://www.yahoo.com") openStream)
#

; assign the InputStream associated with the URL to urlStream
user=> (def urlStream (. (new URL "http://www.yahoo.com") openStream))
#'user/urlStream
; print its value. prints object reference
user=> urlStream
#

; import multiple classes at a time
user=> (import '(java.io BufferedReader IOException InputStreamReader))
java.io.InputStreamReader

; create an InputStreamReader from the urlStream
; use an import to first import the InputStreamReader
user=> (def inputStream (new InputStreamReader urlStream))
#'user/inputStream

; create a BufferedReader from the InputStream
; use an import to first import the BufferedReader
user=> (def bufferedReader (new BufferedReader inputStream))
#'user/bufferedReader

No comments:

Post a Comment