There is a BookView.class that has a private method defined as below
public class BookView{
private boolean importBook(String epubBookPath){
//The function that adds books to database.
}
}
I am trying to call this function from a different package. My code is
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
/*Now we add the book information to the sqlite file.*/
TextView textView=(TextView)findViewById(R.id.textView1);
String filename = textView.getText().toString();
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String epubBookPath = baseDir+filename;
Log.i("epubBookPath:",epubBookPath); //No errors till here!
try {
Method m=BookView.class.getDeclaredMethod("importBook");
m.setAccessible(true);//Abracadabra
//I need help from here! How do i pass the epubBookPath to the private importBook method.
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Intent in = new Intent(getApplicationContext(),
CallEPubUIActivity.class);
startActivity(in);
}
EDIT:
I found another public method in the jar file which is doing the above work.
public void jsImportBook(String epubBookPath) {
if (!BookView.this.importBook(epubBookPath))
return;
BookView.this.createBookshelf();
}
If you want to do that you should make it public or make a public wrapper method it.
If thats not possible, you can work your way around it, but thats ugly and bad and you should have really good reasons to do so.
public boolean importBook(String epubBookPath){
//The function that adds books to database.
}
or
public boolean importBookPublic(String epubBookPath){
return importBook(epubBookPath);
}
private boolean importBook(String epubBookPath){
//The function that adds books to database.
}
Also note that if you CAN'T access the method directly in a third-party library than it is most likely INTENDED that way. Take a look at the call hierarchy of the private method and see if you find a public method that does the call to the private one and that also does what you need.
Libraries are often designed in a way that a public method does some checking (all Parameters given, authenticated etc.) and then pass the call to the private method to do the actual work. You almost never want to work around that process.
With reflection, you'll need an instance of BookView to invoke the method with (unless it's a static method).
BookView yourInstance = new BookView();
Method m = BookView.class.getDeclaredMethod("importBook");
m.setAccessible(true);//Abracadabra
Boolean result = (Boolean) m.invoke(yourInstance, "A Path"); // pass your epubBookPath parameter (in this example it is "A Path"
The method you are looking for is Method#invoke(Object, Object...)
Use reflection to get you method and set Accessible as true, then invoke the method using BookView Object instance and required parameters(path string) using statement as below:
Boolean result = (Boolean)method.invoke(bookObject, epubBookPath);
Sample code as below:
Method method = BookView.getDeclaredMethod("importBook");
method.setAccessible(true);
Boolean result = (Boolean)method.invoke(bookObject, epubBookPath);
Private methods cannot be accessed outside the class it is defined.
Make it Public.
I am writing a game engine in which I need to analyze every single class that is mentioned in my program. As this is a game engine, it is to be attached to a client's project as a JAR file. From within that JAR file I need to be able to scan every class that is being used by the client.
So I thought that I should create a custom ClassLoader! By overriding ClassLoader I can take a look at every class that is being used as it is loaded.
I started playing around a bit with ClassLoaders. Here is what I did:
(I stole this classloader from JavaWorld just to play around with it)
public class SimpleClassLoader extends ClassLoader {
private HashMap<String, Class> classes = new HashMap<String, Class>();
public SimpleClassLoader() {
}
/**
* This sample function for reading class implementations reads
* them from the local file system
*/
private byte getClassImplFromDataBase(String className)[] {
System.out.println(" >>>>>> Fetching the implementation of "+className);
byte result[];
try {
FileInputStream fi = new FileInputStream("store\\"+className+".impl");
result = new byte[fi.available()];
fi.read(result);
return result;
} catch (Exception e) {
/*
* If we caught an exception, either the class wasnt found or it
* was unreadable by our process.
*/
return null;
}
}
/**
* This is a simple version for external clients since they
* will always want the class resolved before it is returned
* to them.
*/
public Class loadClass(String className) throws ClassNotFoundException {
return (loadClass(className, true));
}
/**
* This is the required version of loadClass which is called
* both from loadClass above and from the internal function
* FindClassFromClass.
*/
public synchronized Class loadClass(String className, boolean resolveIt)
throws ClassNotFoundException {
Class result;
byte classData[];
System.out.println(className);
System.out.println(" >>>>>> Load class : "+className);
/* Check our local cache of classes */
result = (Class)classes.get(className);
if (result != null) {
System.out.println(" >>>>>> returning cached result.");
return result;
}
/* Check with the primordial class loader */
try {
result = super.findSystemClass(className);
System.out.println(" >>>>>> returning system class (in CLASSPATH).");
return result;
} catch (ClassNotFoundException e) {
System.out.println(" >>>>>> Not a system class.");
}
/* Try to load it from our repository */
classData = getClassImplFromDataBase(className);
if (classData == null) {
throw new ClassNotFoundException();
}
/* Define it (parse the class file) */
result = defineClass(classData, 0, classData.length);
if (result == null) {
throw new ClassFormatError();
}
if (resolveIt) {
resolveClass(result);
}
classes.put(className, result);
System.out.println(" >>>>>> Returning newly loaded class.");
return result;
}
}
Then I decided to test it:
public class Test
{
public static void main(String args[]) throws ClassNotFoundException
{
SimpleClassLoader s = new SimpleClassLoader();
Thread.currentThread().setContextClassLoader(s);
Foo myfoo = new Foo(); //local class
ArrayList myList = new ArrayList(); //class from JAR file
//both should have been loaded from my SimpleClassLoader
System.out.println(s + "\n\tshould be equal to\n" + myfoo.getClass().getClassLoader());
System.out.println("\tand also to: \n" + myList.getClass().getClassLoader());
/*
OUTPUT:
SimpleClassLoader#57fee6fc
should be equal to
sun.misc.Launcher$AppClassLoader#51f12c4e
and also to:
null
***
bizarre results: why are ArrayList and Foo not being loaded by my classloader?
*/
}
}
Is creating a custom ClassLoader the correct approach to the problem described at the top?
Why is the system class loader being invoked? How do I force the JVM to use MY classloader, for ALL threads? (not just the first thread, I want every new thread created to automatically use my classloader)
It is my understanding that via the "delegation system", the parent ClassLoader gets the first try at loading the class; this may be the reason my ClassLoader isn't loading anything. If I am correct, how to I disable this feature? How do I get MY classloader to do the loading?
The instrumentation api would be a natural fit for what I think you're trying to do
http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html
It lets you intercept classes as they are loaded by the JVM - normally to modify them, but you are given the byte array to play with so I can see no reason why you couldn't perform any required analysis without actually modifying.
This would let you analyse classes before they are loaded. I'm not entirely clear on what it is you are trying to achieve, but if you can analyse the classes after they are loaded then you could simply open and parse the contents of all jars on the classpath.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
You can create various Java code templates in Eclipse via
Window > Preferences > Java > Editor > Templates
e.g.
sysout is expanded to:
System.out.println(${word_selection}${});${cursor}
You can activate this by typing sysout followed by CTRL+SPACE
What useful Java code templates do you currently use? Include the name and description of it and why it's awesome.
I am looking for an original/novel use of a template rather than a built-in existing feature.
Create Log4J logger
Get swt color from display
Syncexec - Eclipse Framework
Singleton Pattern/Enum Singleton Generation
Readfile
Const
Traceout
Format String
Comment Code Review
String format
Try Finally Lock
Message Format i18n and log
Equalsbuilder
Hashcodebuilder
Spring Object Injection
Create FileOutputStream
The following code templates will both create a logger and create the right imports, if needed.
SLF4J
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);
Log4J 2
${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)}
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class);
Log4J
${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);
Source.
JUL
${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());
Some additional templates here: Link I -
Link II
I like this one:
readfile
${:import(java.io.BufferedReader,
java.io.FileNotFoundException,
java.io.FileReader,
java.io.IOException)}
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(${fileName}));
String line;
while ((line = in.readLine()) != null) {
${process}
}
}
catch (FileNotFoundException e) {
logger.error(e) ;
}
catch (IOException e) {
logger.error(e) ;
} finally {
if(in != null) in.close();
}
${cursor}
UPDATE: The Java 7 version of this template is:
${:import(java.nio.file.Files,
java.nio.file.Paths,
java.nio.charset.Charset,
java.io.IOException,
java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
Charset.forName("UTF-8"))) {
String line = null;
while ((line = in.readLine()) != null) {
${cursor}
}
} catch (IOException e) {
// ${todo}: handle exception
}
Format a string
MessageFormat - surround the selection with a MessageFormat.
${:import(java.text.MessageFormat)}
MessageFormat.format(${word_selection}, ${cursor})
This lets me move a cursor to a string, expand the selection to the entire string (Shift-Alt-Up), then Ctrl-Space twice.
Lock the selection
lock - surround the selected lines with a try finally lock. Assume the presence of a lock variable.
${lock}.acquire();
try {
${line_selection}
${cursor}
} finally {
${lock}.release();
}
NB ${line_selection} templates show up in the Surround With menu (Alt-Shift-Z).
I know I am kicking a dead post, but wanted to share this for completion sake:
A correct version of singleton generation template, that overcomes the flawed double-checked locking design (discussed above and mentioned else where)
Singleton Creation Template:
Name this createsingleton
static enum Singleton {
INSTANCE;
private static final ${enclosing_type} singleton = new ${enclosing_type}();
public ${enclosing_type} getSingleton() {
return singleton;
}
}
${cursor}
To access singletons generated using above:
Singleton reference Template:
Name this getsingleton:
${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();
Append code snippet to iterate over Map.entrySet():
Template:
${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
${keyType} ${key} = ${entry}.getKey();
${valueType} ${value} = ${entry}.getValue();
${cursor}
}
Generated Code:
for (Entry<String, String> entry : properties.entrySet())
{
String key = entry.getKey();
String value = entry.getValue();
|
}
For log, a helpful little ditty to add in the member variable.
private static Log log = LogFactory.getLog(${enclosing_type}.class);
Create a mock with Mockito (in "Java statements" context):
${:importStatic('org.mockito.Mockito.mock')}${Type} ${mockName} = mock(${Type}.class);
And in "Java type members":
${:import(org.mockito.Mock)}#Mock
${Type} ${mockName};
Mock a void method to throw an exception:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}
doThrow(${RuntimeException}.class).when(${mock:localVar}).${mockedMethod}(${args});
Mock a void method to do something:
${:import(org.mockito.invocation.InvocationOnMock,org.mockito.stubbing.Answer)}doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object arg1 = invocation.getArguments()[0];
return null;
}
}).when(${mock:localVar}).${mockedMethod}(${args});
Verify mocked method called exactly once:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.times)}
verify(${mock:localVar}, times(1)).${mockMethod}(${args});
Verify mocked method is never invoked:
${:importStatic(org.mockito.Mockito.verify,org.mockito.Mockito.never)}verify(${mock:localVar}, never()).${mockMethod}(${args});
New linked list using Google Guava (and similar for hashset and hashmap):
${import:import(java.util.List,com.google.common.collect.Lists)}List<${T}> ${newName} = Lists.newLinkedList();
Also I use a huge template that generates a Test class. Here is a shortened fragment of it that everyone interested should customize:
package ${enclosing_package};
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.junit.runner.RunWith;
// TODO autogenerated test stub
#RunWith(MockitoJUnitRunner.class)
public class ${primary_type_name} {
#InjectMocks
protected ${testedType} ${testedInstance};
${cursor}
#Mock
protected Logger logger;
#Before
public void setup() throws Exception {
}
#Test
public void shouldXXX() throws Exception {
// given
// when
// TODO autogenerated method stub
// then
fail("Not implemented.");
}
}
// Here goes mockito+junit cheetsheet
Null Checks!
if( ${word_selection} != null ){
${cursor}
}
if( ${word_selection} == null ){
${cursor}
}
One of my beloved is foreach:
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
And traceout, since I'm using it a lot for tracking:
System.out.println("${enclosing_type}.${enclosing_method}()");
I just thought about another one and have found it over the Internet some day, const:
private static final ${type} ${name} = new ${type} ${cursor};
A little tip on sysout -- I like to renamed it to "sop". Nothing else in the java libs starts with "sop" so you can quickly type "sop" and boom, it inserts.
Throw an IllegalArgumentException with variable in current scope (illarg):
throw new IllegalArgumentException(${var});
Better
throw new IllegalArgumentException("Invalid ${var} " + ${var});
Nothing fancy for code production - but quite useful for code reviews
I have my template coderev low/med/high do the following
/**
* Code Review: Low Importance
*
*
* TODO: Insert problem with code here
*
*/
And then in the Tasks view - will show me all of the code review comments I want to bring up during a meeting.
Some more templates here.
Includes:
Create a date object from a particular date
Create a new generic ArrayList
Logger setup
Log with specified level
Create a new generic HashMap
Iterate through a map, print the keys and values
Parse a time using SimpleDateFormat
Read a file line by line
Log and rethrow a caught exeption
Print execution time of a block of code
Create periodic Timer
Write a String to a file
slf4j Logging
${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOGGER = LoggerFactory
.getLogger(${enclosing_type}.class);
Bean Property
private ${Type} ${property};
public ${Type} get${Property}() {
return ${property};
}
public void set${Property}(${Type} ${property}) {
${propertyChangeSupport}.firePropertyChange("${property}", this.${property}, this.${property} = ${property});
}
PropertyChangeSupport
private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}
Post Java 7, a great way to set up loggers which need (or prefer) static references to the enclosing class is to use the newly introduced MethodHandles API to get the runtime class in a static context.
An example snippet for SLF4J is:
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Aside from being a simple snippet in any IDE, it is also less brittle if you refactor certain functionality into another class because you won't accidentally carry the class name with it.
Invoke code on the GUI thread
I bind the following template to the shortcut slater to quickly dispatch code on the GUI thread.
${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
${cursor}
}
});
When testing around with code I sometimes missed out on deleting some syso s. So I made myself a template called syt.
System.out.println(${word_selection}${});//${todo}:remove${cursor}
Before I compile I always check my TODOs and will never forget to delete a System.out again.
strf -> String.format("msg", args) pretty simple but saves a bit of typing.
String.format("${cursor}",)
Get an SWT color from current display:
Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})
Suround with syncexec
PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
public void run(){
${line_selection}${cursor}
}
});
Use the singleton design pattern:
/**
* The shared instance.
*/
private static ${enclosing_type} instance = new ${enclosing_type}();
/**
* Private constructor.
*/
private ${enclosing_type}() {
super();
}
/**
* Returns this shared instance.
*
* #returns The shared instance
*/
public static ${enclosing_type} getInstance() {
return instance;
}
And an equalsbuilder, hashcodebuilder adaptation:
${:import(org.apache.commons.lang.builder.EqualsBuilder,org.apache.commons.lang.builder.HashCodeBuilder)}
#Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
The template for the logger declaration is great.
I also create linfo, ldebug, lwarn, lerror for the log levels that I use more often.
lerror:
logger.error(${word_selection}${});${cursor}
Create everything for an event
Since events are kinda a pain to create in Java--all those interfaces, methods, and stuff to write just for 1 event--I made a simple template to create everything needed for 1 event.
${:import(java.util.List, java.util.LinkedList, java.util.EventListener, java.util.EventObject)}
private final List<${eventname}Listener> ${eventname}Listeners = new LinkedList<${eventname}Listener>();
public final void add${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.add(listener);
}
}
public final void remove${eventname}Listener(${eventname}Listener listener)
{
synchronized(${eventname}Listeners) {
${eventname}Listeners.remove(listener);
}
}
private void raise${eventname}Event(${eventname}Args args)
{
synchronized(${eventname}Listeners) {
for(${eventname}Listener listener : ${eventname}Listeners)
listener.on${eventname}(args);
}
}
public interface ${eventname}Listener extends EventListener
{
public void on${eventname}(${eventname}Args args);
}
public class ${eventname}Args extends EventObject
{
public ${eventname}Args(Object source${cursor})
{
super(source);
}
}
If you have events that share a single EventObject, just delete the customized one inserted by the template and change the appropriate parts of raise___() and on____().
I had written a nice, little, elegant eventing mechanism using a generic interface and generic class, but it wouldn't work due to the way Java handles generics. =(
Edit:
1) I ran into the issue where threads were adding/removing listeners while an event was taking place. The List can't be modified while in use, so I added synchronized blocks where the list of listeners is being accessed or used, locking on the list itself.
Insert test methods should-given-when-then
I saw a similar version to this one recently while pair programming with a very good developer and friend, and I think it could be a nice addition to this list.
This template will create a new test method on a class, following the Given - When - Then approach from the behavior-driven development (BDD) paradigm on the comments, as a guide for structuring the code. It will start the method name with "should" and let you replace the rest of the dummy method name "CheckThisAndThat" with the best possible description of the test method responsibility. After filling the name, TAB will take you straight to the // Given section, so you can start typing your preconditions.
I have it mapped to the three letters "tst", with description "Test methods should-given-when-then" ;)
I hope you find it as useful as I did when I saw it:
#Test
public void should${CheckThisAndThat}() {
Assert.fail("Not yet implemented");
// Given
${cursor}
// When
// Then
}${:import(org.junit.Test, org.junit.Assert)}
Spring Injection
I know this is sort of late to the game, but here is one I use for Spring Injection in a class:
${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};
#Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
this.${var_name} = ${var_name};
}
public ${class_to_inject} get${class_to_inject}() {
return this.${var_name};
}
Here is a constructor for non-instantiable classes:
// Suppress default constructor for noninstantiability
#SuppressWarnings("unused")
private ${enclosing_type}() {
throw new AssertionError();
}
This one is for custom exceptions:
/**
* ${cursor}TODO Auto-generated Exception
*/
public class ${Name}Exception extends Exception {
/**
* TODO Auto-generated Default Serial Version UID
*/
private static final long serialVersionUID = 1L;
/**
* #see Exception#Exception()
*/
public ${Name}Exception() {
super();
}
/**
* #see Exception#Exception(String)
*/
public ${Name}Exception(String message) {
super(message);
}
/**
* #see Exception#Exception(Throwable)
*/
public ${Name}Exception(Throwable cause) {
super(cause);
}
/**
* #see Exception#Exception(String, Throwable)
*/
public ${Name}Exception(String message, Throwable cause) {
super(message, cause);
}
}
I like a generated class comment like this:
/**
* I...
*
* $Id$
*/
The "I..." immediately encourages the developer to describe what the class does. I does seem to improve the problem of undocumented classes.
And of course the $Id$ is a useful CVS keyword.
I've had a lot of use of these snippets, looking for null values and empty strings.
I use the "argument test"-templates as the first code in my methods to check received arguments.
testNullArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
You may want to change the exception message to fit your company's or project's standard. However, I do recommend having some message that includes the name of the offending argument. Otherwise the caller of your method will have to look in the code to understand what went wrong. (A NullPointerException with no message produces an exception with the fairly nonsensical message "null").
testNullOrEmptyStringArgument
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
You can also reuse the null checking template from above and implement this snippet to only check for empty strings. You would then use those two templates to produce the above code.
The above template, however, has the problem that if the in argument is final you will have to amend the produced code some (the ${varName} = ${varName}.trim() will fail).
If you use a lot of final arguments and want to check for empty strings but doesn't have to trim them as part of your code, you could go with this instead:
if (${varName} == null) {
throw new NullPointerException(
"Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
throw new IllegalArgumentException(
"Illegal argument. The argument cannot be an empty string: ${varName}");
}
testNullFieldState
I also created some snippets for checking variables that is not sent as arguments (the big difference is the exception type, now being an IllegalStateException instead).
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
testNullOrEmptyStringFieldState
if (${varName} == null) {
throw new IllegalStateException(
"Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
throw new IllegalStateException(
"Illegal state. The variable or class field " +
"cannot be an empty string: ${varName}");
}
testArgument
This is a general template for testing a variable. It took me a few years to really learn to appreciate this one, now I use it a lot (in combination with the above templates of course!)
if (!(${varName} ${testExpression})) {
throw new IllegalArgumentException(
"Illegal argument. The argument ${varName} (" + ${varName} + ") " +
"did not pass the test: ${varName} ${testExpression}");
}
You enter a variable name or a condition that returns a value, followed by an operand ("==", "<", ">" etc) and another value or variable and if the test fails the resulting code will throw an IllegalArgumentException.
The reason for the slightly complicated if clause, with the whole expression wrapped in a "!()" is to make it possible to reuse the test condition in the exception message.
Perhaps it will confuse a colleague, but only if they have to look at the code, which they might not have to if you throw these kind of exceptions...
Here's an example with arrays:
public void copy(String[] from, String[] to) {
if (!(from.length == to.length)) {
throw new IllegalArgumentException(
"Illegal argument. The argument from.length (" +
from.length + ") " +
"did not pass the test: from.length == to.length");
}
}
You get this result by calling up the template, typing "from.length" [TAB] "== to.length".
The result is way funnier than an "ArrayIndexOutOfBoundsException" or similar and may actually give your users a chance to figure out the problem.
Enjoy!
I use this for MessageFormat (using Java 1.4). That way I am sure that I have no concatenations that are hard to extract when doing internationalization
i18n
String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);
Also for logging:
log
if(logger.isDebugEnabled()){
String msg = "${message}"; //NLS-1
Object[] params = {${params}};
logger.debug(MessageFormat.format(msg, params));
}
My favorite few are...
1: Javadoc, to insert doc about the method being a Spring object injection method.
Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
*
* #param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance
2: Debug window, to create a FileOutputStream and write the buffer's content's to a file.
Used for when you want to compare a buffer with a past run (using BeyondCompare), or if you can't view the contents of a buffer (via inspect) because its too large...
java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();