Java for C# Programmers 9: Reflection

Reflection

Java has full-fledged reflection powers.

    List ll = new LinkedList();

    ll.add(13);
    ll.add('A');
    ll.add(true);
    ll.add(3.14);
    ll.add("Java");

    for(Object o: ll)
        System.out.printf("%s -> %s \n", o, o.getClass());

puts out

13 -> class java.lang.Integer 
A -> class java.lang.Character 
true -> class java.lang.Boolean 
3.14 -> class java.lang.Double 
Java -> class java.lang.String 

is / as / instanceof

The is operator in C# has an equivalent in Java: instanceof.
No equivalent for the as operator does exist in Java. You could use this function as a replacement.

public static  T as(Class c, Object o)
{
    if(c.isInstance(o))
        return c.cast(o);
    return null;
}

Print Class Information Via Reflection

To print all available information about a type you can use the following class ReflectionInfo.

static public class ReflectionInfo
{
    private static Constructor [] constructors;
    private static Field[] fields;
    private static Method[] methods;

    public static void main(String[] args)
    {
        GetInfo("java.lang.String");
        PrintInfo();
    }

    private static void GetInfo(String className)
    {
        try
        {
            // create class object
            Class cl = Class.forName(className); 
            constructors = cl.getConstructors();
            fields = cl.getDeclaredFields();
            methods = cl.getMethods();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private static void PrintInfo()
    {
        PrintConstructors();
        PrintFields();
        PrintMethods();
    }

    private static void PrintConstructors()
    {
        System.out.println("\nConstructors");
        for(int i = 0; i < constructors.length; ++i)
            System.out.printf("%02d: %s \n", i+1, constructors[i]);
    }

    private static void PrintFields()
    {
        System.out.println("\nFields");
        for(int i = 0; i < fields.length; ++i)
            System.out.printf("%02d: %s \n", i+1, fields[i]);
    }

    private static void PrintMethods()
    {
        System.out.println("\nMethods");
        for(int i = 0; i < methods.length; ++i)
            System.out.printf("%02d: %s \n", i+1, methods[i]);
    }
}

The code above prints the following.

Constructors
01: public java.lang.String(byte[]) 
02: public java.lang.String(byte[],int,int)

    ... (snip) ...

11: public java.lang.String(java.lang.String) 
12: public java.lang.String() 
13: public java.lang.String(byte[],int,int,java.lang.String) 
            throws java.io.UnsupportedEncodingException 
14: public java.lang.String(byte[],int) 
15: public java.lang.String(byte[],int,int,int) 

Fields
01: private final char[] java.lang.String.value 
02: private int java.lang.String.hash 
03: private static final long java.lang.String.serialVersionUID 
04: private static final java.io.ObjectStreamField[] 
            java.lang.String.serialPersistentFields 
05: public static final java.util.Comparator
            java.lang.String.CASE_INSENSITIVE_ORDER 
06: private static final int java.lang.String.HASHING_SEED 
07: private transient int java.lang.String.hash32 

Methods
01: public boolean java.lang.String.equals(java.lang.Object) 
02: public java.lang.String java.lang.String.toString() 
03: public int java.lang.String.hashCode() 
04: public int java.lang.String.compareTo(java.lang.Object) 
05: public int java.lang.String.compareTo(java.lang.String)

    ... (snip) ...

64: public java.lang.String
                   java.lang.String.toUpperCase(java.util.Locale) 
65: public java.lang.String java.lang.String.toUpperCase() 
66: public java.lang.String java.lang.String.trim() 
67: public final void java.lang.Object.wait(long,int) 
            throws java.lang.InterruptedException 
68: public final native void java.lang.Object.wait(long) 
            throws java.lang.InterruptedException 
69: public final void java.lang.Object.wait() 
            throws java.lang.InterruptedException 
70: public final native java.lang.Class 
            java.lang.Object.getClass() 
71: public final native void java.lang.Object.notify() 
72: public final native void java.lang.Object.notifyAll() 

Calling Constructors And Methods via Reflection

Check this example to see how constructors and methods can be called via reflection.

static public class ReflectionInfo
{
    private static Constructor[] constructors;
    private static Field[] fields;
    private static Method[] methods;

    public static void main(String[] args)
    {
        GetInfo("java.lang.String");
        UseReflectedMethods();
    }

    private static void UseReflectedMethods()
    {
        try
        {
            Constructor cons = null;
            // look for the String(String) constructor
            for (Constructor c : constructors)
            {
                if (c.toString().contains("(java.lang.String)"))
                {
                    cons = c;
                    break;
                }
            }

            // Create a new instance of a String 
            // with a String parameter. 
            String s = (String) cons.newInstance("abcde");
            System.out.println(s);    // -> abcde

            Method met = null;
            // look for the concat method
            for (Method m: methods)
            {
                if (m.toString().contains("concat"))
                {
                    met = m;
                    break;
                }
            }

            // Call a method on String s.
            String t = (String) met.invoke(s, " xyz");
            System.out.println(t);    // -> abcde xyz

        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }

    private static void GetInfo(String className)
    {
        try
        {
            // create class object
            Class cl = Class.forName(className); 
            constructors = cl.getConstructors();
            fields = cl.getDeclaredFields();
            methods = cl.getMethods();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Java for C# Programmers 8: Applets

Java Applets

A Java applet is a Java program that is usually run in a web browser. The Java bytecode is hosted on a web server and delivered to the user. In the user’s browser, the applet is run by a JVM which is part of the browser, usually in form of a plugin.

There are these main differences to a normal Java app.

  1. The main class must be derived from java.applet.Applet or, for a Swing applet from javax.swing.JApplet.
  2. There is no static void main(..) function. Instead, an applet has several functions that can and should be overridden by your applet. They are explained in the template below.
  3. No size inside the applet. Size is taken from HTML.
  4. An applet is closed, when the browser (or tab) is closed.
  5. An applet can not have a title, only the website can have it.
public class AppletTemplate extends Applet  // or JApplet
{
    // Is called once when the applet is first loaded 
    // into the browser.
    public void init() { }

    // Is called after loading of the applet, whenever the 
    // applet becomes visible. It then should start its execution.
    public void start() { }

    // Is called when the applet becomes invisible, e.g. because some 
    // other window is put in front of the applet. The applet then 
    // should stop its execution.
    public void stop() { }

    // Is called, when the applet is removed from memory. An applet
    // that uses resources must free them here.  
    public void destroy() { }

    // Is called when something shall be painted. 
    public void paint (Graphics g) { }
}

How to Test Your Java Applet Locally

It is easy to test it via Eclipse. When the active window contains an applet and you start debugging, automatically Eclipse’s applet viewer starts and shows the applet.

But at some point, you’ll probably want to see your applet running in a browser.

To be able to view an applet in the browser, a link to the applet has to be put into some html code. You can use the deprecated applet or the newer object tag. An example for both follows. The applet class here is ColorMixerClass in package Applets.


    
        

ColorMixer Java Applets

Gotcha: There are some minutiae which you need to know.

  1. Use a fully qualified URL-like path in the archive parameter, with leading file://. Just giving C:\Data\Java-works\bin\ColorMixer.jar in the example above will lead to an IllegalArgumentException: name.
  2. In the code or classid parameter, give the full path of the applet class inside the jar. Otherwise you’ll get an ClassNotFoundException
  3. Astounding, but true: Some of the latest Java update put a higher security restriction on applets coming from the local file system, than it does for applets from the internet.
    So even if you can run Java applets from the internet in your browser, it is probable that you cannot run the applet that you’ve written yourself and that is located on your local harddrive. If that is the case, you need to lower your computer’s security settings.

    1. Go to your Control Panel/Java/Configure Java/Security and put the security to Medium.
    2. After changing the security level, you might need to end some hanging browser and/or Java processes until you can get your applet to run.

Java for C# Programmers 7: Binaries

Source Code and Binaries Organization

Source Code

  • Every source code file must contain maximally one public class. There may be more than one non-public classes.
  • The name of the public class – if there is any – must be identical to the first part of the source code file.
  • Source code file: MyLove.java -> public class MyLove
  • Partial classes are not allowed.

Binaries

  • From MyLove.java a MyLove.class is created. The .class file contains the Java bytecode of the associated .java file.
  • From .class files and ressources a XYZ.jar (Java ARchive) can be created. A jar file is mainly a zip file of its contents, maybe with an added metadata file and the file extension .jar instead of .zip.
  • In principle, a jar file is something similar to an assembly or dll in .NET. The term jar hell is well known to Java developers.
  • A jar file can be a runnable jar file or a library.
  • The jar commandline program can be used to create or inspect jar files. It is a zip program with tar like syntax.
  • jar tvf XYZ.jar shows a verbose content listing of XYZ.jar.
  • In Eclipse, use File - Export - Java to create a jar file.

Runnable Jar Files

  • A runnable jar file is a an ordinary jar file with an added manifest file which contains an entry for the main class.
  • The main class must have a public static void main(String[] args) method. This method will be called when the jar is run.
  • The manifest file is an ordinary UTF-8 encoded text file called MANIFEST.MF located in the folder META-INF. It can contain information about signing, version control, package sealing and others.

An entry for a main class may look like this

Main-Class: Gaming.TraceOfDeathEngine

Here, Gaming is the package name and TraceOfDeathEngine is the class name.

Create a Runnable Jar, V1

  • This method will pack all the files of the project into the jar file. There is no way here to select which files shall be included in the jar and which shall not. But as a jar file is an ordinary zip, you can remove superfluous files afterwards. Or see method 2.
  • In Eclipse use File - Export - Java - Runnable JAR file to create an executable jar file.
  • On the the following page, select your main class under Launch configuration and input the file path of the jar file that shall be created.

Create a Runnable Jar, V2

  • This method will pack only selected files of the project into the jar file.
  • In Eclipse in the Package Explorer select the project or package which contains most of the stuff that shall be included in the jar.
  • Use File - Export - Java - JAR file. (Do not select Runnable JAR here. You can create a runnable jar anyway.)
  • On the the following page, select the Java- and resource files you want to have in the jar. Also set the export destination.
  • On the fourth page, select Generate the manifest file at the top and at the bottom select your Main class.

Create a Runnable Jar, V3

If you don’t use Eclipse or want to automate creating a runnable jar file, you can use the jar utility.
An example:

jar -cvfe troz.jar  Gaming.TrodEngine Gaming

The command line above explained:

c: create new jar file
v: be verbose
f: specify archive file name
e: pass entry point, create manifest automatically
troz.jar:          the archive file name
Gaming.TrodEngine: the entry point is class `TrodEngine` 
                   in package `Gaming`
Gaming:            the folder to include in the jar. 

If you have already a created manifest you can pass it to the jar utility with the m option. Jar will then add it to the jar file as META-INF/MANIFEST.MF

jar cvfm trox.jar  mf.txt Gaming

As said, the jar utility program has tar like syntax. So the line above means:

c: create new jar file
v: be verbose
f: specify archive file name
m: include manifest file
trox.jar: the archive file name
mf.txt:   the manifest file name
Gaming:   the folder to include in the jar. 

Some quirks of the jar utility:

  • The archive file and the manifest file (or the entrys point) must be specified in the same order as the f , m and e flags.
  • If any “file” is a directory then it is processed recursively.
  • It is not allowed to split the options up. tar cvf trox.jar m MAN Gaming is not possible.

Start a Java Program On Windows

On Windows, when Java is installed properly, you can doubleclick a runnable jar file from Windows Explorer to start it. Or you can create a shortcut and place it onto the desktop and use the shortcut to start the java program. You cannot attach such a shortcut to the taskbar, though.

To start a runnable abc.jar via commandline and pass parameters param1 and param2 to the main classes main method, just call

java.exe -jar abc.jar param1 param2

You can also start a Java program if you don’t have a jar file, but only the needed .class files. To do this Java.exe must be called from the bin directory one level above the package name. When the class to start is called MyLove and resides in the package Xcv and the parameters param1 and param2 shall be passed, the command line shall look like this:

java.exe Xcv.MyLove param1 param2

Create a Windows .exe File

To create an executable Windows exe file, you can use launch4j. More details about launch4j are given there (scroll down to method 3 of 3): http://www.wikihow.com/Create-an-Executable-File-from-Eclipse

There are several other possibilities to create a Windows .exe file, namely using Java Web Start technology or an Ahead Of Time compiler or …
A good overview about the available technologies is given here:
http://www.excelsior-usa.com/articles/java-to-exe.html

Libraries

Jar files may be used as libraries and there are zillions of publicly available jar libraries.

This example shows you how to add a MySQL connector library to your Java project.

  1. Download the zipped Java connector for MySQL from there:
    http://dev.mysql.com/downloads/connector/j. Select Platform Independent and ZIP Archive.
  2. Extract the package and copy just the mysql-connector*.jar file to somwhere below your workspace. I’d recommend a directory called lib which is a sibling of your bin directory.
  3. In Eclipse, add the jar file to your lib path via Project - Properties - Java Build Path - Libraries - Add External Jars...
  4. This will add the library to your project. Afterwards, you’ll see the library in the Package Explorer under Referenced Libraries.

Four Most Essential Firefox Add-Ons And Settings. Plus Eight Extras.

My dear friend Sabrina called and complained about a lot of popup windows and stuff when surfing the web. These are my recommendations for some essential plugins and settings in Firefox. Especially for you, Sabrina.

April 16th 2018, Update: I can no longer recommend using Firefox as they have kicked millions of users and thousands of add-on developers in the a** by disabling many important APIs in FF, which makes it impossible for the add-on developers to adapt. Many of the add-ons recommended below do not work anymore with FF Quantum. I am using Waterfox now. It is a FF fork which wants to keep the old APIs – and all my recommended add-ons work.

Two Most Essential Firefox Add-Ons

An Adblocker

An adblocker the essential add-on. I couldn’t use the web without one. It stops most of all those annoying blinking ads which try to distract you from your work in intrusive and flashy ways.
May 5th 2017, Update: I can no longer recommend Adblock Plus, as it lately often lead to complete hangs of Firefox. I do use now uBlock Origin.
To install, select the given link and there click Add to Firefox. Follow further instructions there.

Flashblock

The second add-on which is a couldn’t live without it is Flashblock. It replaces all the Flash stuff that tries to capture your attention in disturbing ways with a nice and silent f icon flashblock-f. If you really want to see the video or hear the music behind the f, just click the f.
To install it, click here and there Add to Firefox. Follow further instructions there.

Three Most Essential Firefox Settings

Block Popup Windows

  1. Open the Settings dialog in Firefox
  2. Select the Content tab.
  3. At the top, check Block Popup-Windows
  4. Press the Ok button.

Switch Off Gif Animations

First check out this site. Are there a lot of smilies winking, blinking, smiling, jumping around and even vomiting? So that you would get crazy if you looked at it for more than ten seconds? Yes? These are animated gifs. Not that I dislike them. No. I hate them.

Thank god, they’ve built something into Firefox to switch them off. It may seem a bit complicated for everyday users, but it is worth it.

  1. Type about:config into the address bar of firefox. about-cfg-address
  2. Ignore the following warning about The guarantee ends here and press the button I’ll be cautious, really.
  3. A huge list of settings will be shown. Type image.animation_mode into the search bar at the top so that the list will be reduced to one entry. The page then will look like this:
    about_config_image_anim
  4. Double-click the marked normal in the line. In the upcoming dialog, type in none and press ok. Close the about:config tab.
  5. Revisit the animated smilies page. You should look into complete quiescence now. Ah. This calmness. How relieving. Like a cool breath on a hot and humid day.

Turn Off Spell Checking

13 Nov 2017 Update Some time ago, those FF developers thought it would be a good idea to turn on a spell checker by default. It is not. You can turn it off via Preferences/Advanced/Check my spelling as I type.

Some Extra Add-Ons I Like

  1. Leechblock is from heaven for people who tend to surf the web (-hell) too much.
  2. Video DownloadHelper makes it possible to download videos from Youtube.
  3. With Fireshot, you can make screen shots of web pages that are too big to fit on the screen at once.
  4. JS Switch adds a toolbar button to the browser with which you can switch off and on JavaScript with one click.
  5. LEO Search adds a context menu entry to translate selected words.
  6. Vertical Toolbar lets you move your bookmarks and other buttons from a horizontal toolbar into a vertical one. This is very useful with the wide screens in use nowadays.
  7. Morning Coffee This extension lets you organize websites by day and open them up simultaneously as part of your daily routine. This is handy if you read want to read different newssites daily. I like it much.
  8. Firebug is an addon which is essential for all people creating web pages in one or another way. It helps you so much in debugging and creating HTML and CSS.
  9. Web Developer got a lot of five star reviews. I have to check it out.

Did I miss an essential add-on or setting? What are your favourites? I’d love to read about your opinions in the comments.

Java Colormixer Applet

My First Java Applet: A Color Mixer

It has got these features:

  • The background shows the mixed RGB color.
  • The background of the red slider shows a color (r,0,0) where r is the selected red value. The sliders for green and blue are equivalent.
  • The color of the labels on the background are adapted to the background color so that they are always readable.
  • The color of each slider’s labels are adapted to the slider’s background so that they are always readable.