CSCE 314 Lecture 33

From Notes
Jump to navigation Jump to search

« previous | Friday, November 18, 2011 | next »


Java Reflections

  • java.lang.Class
  • java.lang.reflect


We can get a Class Object by calling o.getClass() on a class or an instance o.

Once we have a Class object, we can getSuperClass(), getClasses() (public nested classes), etc.


Example

A program to pretty-print a class.

Class c = Class.forName(className);
System.out.println(c + " {");

int mods;
Field fields[] = c.getDeclaredFields();
for (Field f : fields) {
    if (!Modifier.isPrivate(f.getModifiers()) && !Modifier.isProtected(f.getModifiers()))
        System.out.println("\t" + f);
}

Constructor[] constructors = c.getConstructors();
for (Constructor con : constructors) {
    System.out.println("\t" + con);
}

Method methods[] = c.getDeclaredMethods();
for (Method m : methods) {
    if (!Modifier.isPrivate(m.getModifiers())) {
        System.out.println("\t" + m);
    }
}

System.out.println("}");

Dynamic method invocation.

// let this be a method of object x
public void work(int i, String s) {
    System.out.printf("Called: i=%d, s=%s%n", i, s);
}

// somewhere else...
Class clX = x.getClass();
Class[] argTypes = { int.class, string.class };         // array of matching Class types for method search
Method worker = clX.getMethod("work", argTypes);        // find method for given name and types
Object[] theData = { 42, "Chocolate Chips" };           // give invocation arguments as array
worker.invoke(x, theData);                              // invoke/exectue the method


Concurrency in Java

Parallel computing with threads: Several activities can occur simultaneously.

Most of the electronic stuff we do every day has concurrent processes running in the background.

Math says concurrent programming is difficult. The truth is: concurrent programming is very difficult... at least depending on the tools and programming languages used...

In pure languages with referential transparency (Haskell), concurrency can be easy! Other languages:

  • C/C++ have libraries (not part of the language itself)
  • Java concurrency is almost part of the language and partially defined in its library