Loader/Launcher – A Pattern to Bootstrap Java Applications

There is still a great number of Java developers out there who are not doing web apps. They use the JDK’s Java launcher directly to bootstrap their apps using public static void main() (abbreviated thereafter as PSVM). And if you are one of those developers, you understand the implications of having a large classpath. It is not uncommon to see shell command with no less than a dozen jars listed on the classpath.

Of course over the years many options have been provided to help with this issue. One of the most recent is from Java 6 where you can reduce the length of the command to launch your Java application by specifying wildcards values in the classpath as shown below:

$ java -cp path1/*.jar:path2:/*:path3/*.jar package.name.ClassName

This write up proposes an alternative approach where your code loads your application’s classes programatically. This pattern, named Loader/Launcher, separates the loading of your application’s classes from the booting of your application logic. The idea is to provide your own loader class that will load your classpath then delegates further bootstrapping responsibilities to a launcher class. One benefit of this approach is that your command to launch your application can be reduced to something like this (no matter the size of your class dependency graph):

$ java -jar package.name.ClassName

The Loader/Launcher Pattern

The way that the Loader/Launcher pattern works is to de-entangle class-loading concerns from application execution concerns. The loading of classes is handled by a Main class with a PSVM method. The native Java command-line launcher loads the Main class. The execution of the application is delegated to a launcher class that implements the Launcher interface. The Launcher is instantiated and invoked by the Main class.

Loader/Launcher Sequence

Loader/Launcher Sequence

To implement this pattern, you will need the following high-level components:

  • The Launcher interface that will be used as a starting point for your app.
  • The Main class where a PSVM method is defined.
  • A Launcher implementation to execute the application.

The Launcher Interface

Implementation of this interface is intended to be the starting point of your application’s bootup process. Instead of starting your application directly in the PSVM method, as is done traditionally, you would relocate the logic for your application’s boot up sequence in a class that implements this interface. When the PSVM method is invoked by the native Java launcher, it would delegate the boot sequence of your application to your Launcher instance (see interface below Listing-1).

 

public interface Launcher {
	public int launch(Object ... params);
}

 

Listing-1

This is a simple interface with a single method, launch(). The method takes an array of objects that can be used to pass in arguments to launcher. The method’s signature makes easy to maintain the semantic of PSVM when using the Launcher.

The Main Class

The Main class is designed to be the starting point for the native Java launcher by exposing a PSVM method. The role of this class, in the Loader/Launcher Pattern, is summed up below:
It creates and loads the application’s classpath. Internally, it instantiates a ClassLoader that is used to load the application’s classpath from a specified location.
Once the classpath is in place, it creates an instance of Launcher, from the classpath, to boot up the application by calling launch().

Listing-2 shows the content of a Main class.

 

public class Main {
	private static String CLASSPATH_DIR = "lib";
	private static String LIB_EXT = ".jar";
	private static String LAUNCHER_CLASS = "demo.launcher.AppLauncher";

	private static ClassLoader cl;
	static{
		try {
			cl = getClassLoaderFromPath(
				new File(CLASSPATH_DIR),
				Thread.currentThread().getContextClassLoader()
			);
			Thread.currentThread().setContextClassLoader(cl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Returns a ClassLoader that for the provided path.
	private static ClassLoader getClassLoaderFromPath(File path, ClassLoader parent) throws Exception {
		// get jar files from jarPath
		File[] jarFiles = path.listFiles(new FileFilter() {
			public boolean accept(File file) {
				return file.getName().endsWith(Main.LIB_EXT);
			}
		});
		URL[] classpath = new URL[jarFiles.length];
		for (int j = 0; j < jarFiles.length; j++) {
			classpath[j] = jarFiles[j].toURI().toURL();
		}
		return new URLClassLoader(classpath, parent);
	}

	public static void main(String[] args) throws Exception{
		Launcher launcher = Launcher.class.cast(
			Class.forName(LAUNCHER_CLASS, true, cl).newInstance()
		);
		launcher.launch(new Object[]{"this string is capitalized"});
	}
}

 

Listing-2

The first thing to notice is the static declarations at the start of the listing. The first three declarations setups the “lib” directory as the location for the classpath, provides “.jar” as the file extension, and specifies demo.launcher.AppLauncher as the name of the Launcher class to load from the classpath. The static code block uses method getClassLoaderFromPath() to initialize a URLClassLoader instance (that points to the lib directory) that will serve as the class loader for the rest of the application.

When the public static void main() method in the Main class is invoked (by the Java launcher), it searches and loads an instance of class demo.launcher.AppLauncher which implements Launcher. Then, the code calls Launcher.launch() to delegate the execution of the rest of the application by passing in a String parameter.

The Launcher Class

The Launcher class is responsible for starting up the application-specific logic. Implementation of the launch() method maintains the same signature as the the PSVM method from the Main class to maintain the familiar semantic. Parameters are passed in as arrays of objects and the method is expected to return an integer. A return value of 0 means everything is OK while anything else means something up to the discretion of the implementor. Listing-3 shows a simple implementation of the Launcher class.

 

public class AppLauncher implements Launcher {
	public int launch(Object ... args) {
		String result = org.apache.commons.lang3.text.WordUtils.capitalize((String)args[0]);
		System.out.println (result);
		return 0;
	}
}

 

Listing-3

How It Works

This implementation uses Apache Commons-Lang to capitalize the value of an argument that was passed in. While this is a simple example, it shows exactly how the pattern would work.  When the application is invoked from the command-line using

$ java -jar demo.launcher.Main

The Main class resolves the classpath by loading jars from the jar directory.  The classpath directory contains all jars that satisfies the dependency graph of the application.  In this example the application depends on the Apache-Commons Lang jar.  When Main instantiates its ClassLoader instance, the jar will be added on the classpath and thus be available for use.

An Example

You can download example code that shows how this works from the location below:
An example – https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher

The example comes in three separate projects:

  • Launcher-Api – contains the definition of the Launcher interface.
  • Launcher-Impl – contains an implementation of the Launcher interface.
  • Laucnher-Main – contains the Main class that is used as the starting point of the application.

Conclusion

The Loader/Launcher Pattern is an attempt to decouple two distinct activities that occur when a Java application is started: that of class loading and and application start up. The pattern uses a Main class as the entry point from the Java native launcher and is used to  load the application’s classpath from a given location.  The act of activating the application is then relegated to a Launcher class.  The launcher is responsible for actually starting up the application-specific logic in the code.  Some of the benefit of adopting this pattern is, firstly, the tighter control over how classes are loaded.  You no longer have to rely on the native Java launcher to resolve your classpath.  Another benefit is the separation of concerns for the start up sequence of the app.  The pattern provides a location, the Launcher interface, where to define what should happen when the application itself (not loading of classpath) is starting.  Hope this was helpful.

Reference

https://github.com/vladimirvivien/workbench/tree/master/CustomLauncher - the example

http://code.google.com/p/clamshell-cli/ - tool that uses this pattern

转载于:https://www.cnblogs.com/ouxingning/archive/2012/10/15/bootstrap_java_applications.html

以下是 IconShapeOverride.java 的源代码: ```java package com.android.launcher3.graphics; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Path; import android.graphics.Rect; import android.os.Build; import android.util.Log; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.android.launcher3.Utilities; import com.android.launcher3.icons.GraphicsUtils; import com.android.launcher3.icons.IconProvider; import com.android.launcher3.icons.ShapeData; import com.android.launcher3.util.MainThreadInitializedObject; import com.android.launcher3.util.ResourceBasedOverride; /** * Provides custom icon shapes based on user preferences. */ public class IconShapeOverride extends ResourceBasedOverride { public static final String KEY_PREFERENCE = "pref_override_icon_shape"; private static final String TAG = "IconShapeOverride"; private final IconProvider mIconProvider; public IconShapeOverride(Context context) { this(context, IconProvider.INSTANCE); } @VisibleForTesting public IconShapeOverride(Context context, IconProvider iconProvider) { super(context, KEY_PREFERENCE); mIconProvider = iconProvider; } /** * @return the current shape path, or null if not defined. */ @Nullable public ShapeData getShape() { String pathString = getStringValue(); if (pathString == null) { return null; } try { return ShapeData.parse(pathString); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to parse shape", e); return null; } } /** * @return the current shape path as a {@link Path} instance, or null if not defined. */ @Nullable public Path getShapePath() { ShapeData data = getShape(); return data != null ? data.getPath() : null; } /** * @return the current shape path bounds, or null if not defined. */ @Nullable public Rect getShapeBounds() { ShapeData data = getShape(); return data != null ? data.getBounds() : null; } /** * Returns the shape path for the given context, or null if none is specified. */ public static Path getShapePath(Resources res, SharedPreferences prefs) { IconShapeOverride override = new IconShapeOverride(res); override.setSharedPreferences(prefs); return override.getShapePath(); } /** * Tests whether the current shape is a circle, by checking if all corners of the shape are at * the same distance from the center. */ public boolean isShapeCircle() { Path shape = getShapePath(); if (shape == null) { return false; } Rect bounds = getShapeBounds(); if (bounds == null) { return false; } Rect outBounds = new Rect(); shape.computeBounds(outBounds, true); float centerX = bounds.exactCenterX(); float centerY = bounds.exactCenterY(); float radius = Math.max(centerX - bounds.left, centerY - bounds.top); float maxDeviation = 0; float[] radii = new float[9]; shape.approximate(1f, radii); for (int i = 0; i < radii.length; i += 2) { float deviation = Math.abs(radii[i] - radius); if (deviation > maxDeviation) { maxDeviation = deviation; } } return maxDeviation < GraphicsUtils.EPSILON; } /** * Updates the default icon shape, if the user has not overridden it. */ public static void updateDefaultShape(Context context) { SharedPreferences prefs = Utilities.getPrefs(context); if (prefs.contains(KEY_PREFERENCE)) { return; } IconShapeOverride override = new IconShapeOverride(context); Path path = override.getDefaultShape(); if (path != null) { prefs.edit().putString(KEY_PREFERENCE, ShapeData.toString(path)).apply(); } } /** * @return the default shape path for the current device. */ @Nullable public Path getDefaultShape() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return IconShape.applyMaskIfNeeded(mIconProvider.getDeviceProfile(), mIconProvider.getIconMask()); } return null; } @Override protected void onValueChanged() { super.onValueChanged(); mIconProvider.clearCaches(); } } ``` 该类提供了自定义应用图标的形状的功能,它会根据用户的偏好设置提供自定义图标形状。其中包含了获取、设置、更新默认图标形状等方法。此外,还包含一些辅助方法,如测试当前形状是否为圆形。在 Android Oreo 及以上版本中,会调用 IconShape 类提供的方法来获取默认图标形状。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值