Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Posts Tagged ‘Java

Java | ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

leave a comment »

ERROR: java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.String

Story:
Ok, I hits the above error when I try to loop through the request parameters, and print out all parameter Key and Value.
The ClassCastException is a general exception, it will be thrown when you try to cast an Apple to an Orange. Thats simple!
When the first time I read this exception message, “[Ljava.lang.String; cannot be cast to java.lang.String”, I though there is some typo in the compiler 😛
What is the difference between “[Ljava.lang.String” and “java.lang.String”?
From the wording itself, quite straight forward. The later do not have “[L”, but what is the “[L”?
Thanks for some stupid errors I hit before, I recall that the “[L” is the representation of Array object!

CODE / SOLUTION:
Here is the way I used to print out all parameter Key and Value. I’m not sure its a correct / best way, but its works!

Map paramMap = request.getParameterMap();
Iterator iter = paramMap.entrySet().iterator();
while(iter.hasNext()) {
    Entry<String, String[]> entry =  (Entry<String, String[]>) iter.next();
    String key = entry.getKey();
    String value = entry.getValue()[0];
    logger.debug("key[{}] value[{}]", key, value);
}
Advertisements

Written by Alfred

June 22, 2010 at 20:08

Posted in Java

Tagged with , , ,

Java | How to access Enum’s public method?

leave a comment »

Enum is an enumerated types, a special type in Java that used to hold static information.
Eg: the state of a connection (CONNECTING, CONNECTED, DISCONNECTED, etc), the day (MONDAY, TUESDAY, etc).
Besides of defining a status, we also can include some useful features of the Enum and write it as a method in the Enum.
Here is a simple example I write to show how to access to Enum’s method.

I have a Enum here, named “Day”:

package alfred.playground;

public enum Day {

	MONDAY, TUESDAY,
	WEDNESDAY, THURSDAY,
    FRIDAY, SATURDAY,
    SUNDAY;

	public boolean isWeekday() {
		return (equals(MONDAY) ||
				equals(TUESDAY) ||
				equals(WEDNESDAY) ||
				equals(THURSDAY) ||
				equals(FRIDAY));
	}

	public boolean isWeekend() {
		return (equals(SATURDAY) || equals(SUNDAY));
	}

}

And, here is the test program:

		Day day1 = Day.THURSDAY;
		System.out.println(String.format("[%s] is weekend? [%b]", day1, day1.isWeekend()));
		/*$>  [THURSDAY] is weekend? [false] */

		Day day2 = Day.SATURDAY;
		System.out.println(String.format("[%s] is weekend? [%b]", day2, day2.isWeekend()));
		/*$>  [SATURDAY] is weekend? [true] */

In order to call Enum’s method, we can not just directly call as usual class’s method “myClass.doSomething()”.
Instead, we must assign a value to the Enum before we can invoke the method.

For shorter codes, we can simplified the code by skipping the value assignment line:

		System.out.println(String.format("[%s] is weekend? [%b]", Day.FRIDAY, Day.FRIDAY.isWeekday()));
		/*$>  [FRIDAY] is weekday? [true] */

Written by Alfred

April 2, 2009 at 16:27

Posted in Java

Tagged with ,

Convert ArrayList to Array

leave a comment »

This is a basic Java conversion stuff. I want to convert an ArrayList to a normal Array.
Here is a sample I did and I would like to share it out to anyone who found its useful. 😉

The test driver…

.....
List arrayList_ = new ArrayList();
arrayList_.add("alpha");
arrayList_.add(new String("beta"));
arrayList_.add(new Integer(3));
arrayList_.add(new Float(4.00));
arrayList_.add(new Boolean(true));
.....
Object[] array_ = arrayListToArray(arrayList_);
for (int i=0; i<array_.length; i++) {
    System.out.println("&#91;" + i + "&#93; " + array_&#91;i&#93;);
}
// $>[0] alpha
// $>[1] beta
// $>[2] 3
// $>[3] 4.0
// $>[4] true
.....

The conversion happen here…

private Object[] arrayListToArray(List arrayList) {
    Object[] array = new Object[arrayList.size()];
    arrayList.toArray(array);
    return array;
}

Written by Alfred

December 30, 2008 at 18:11

Posted in Java

Tagged with , , ,

java.lang.IllegalArgumentException: Malformed \uxxxx encoding

with 11 comments

The above error is cause by the baclslash “\” that use in Windows.

I demostrate the error in this simple example.
The example is going to get the File object that being instancial by Spring to do further process.

The java code is looks like this:

public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] {
						"classpath:/alfred/demo/spring/applicationContext.xml"
				});
		
		BeanFactory factory = (BeanFactory) context;
		
		final String myFileBeanName = "myFile";
		File file = (File) factory.getBean(myFileBeanName);
		.....
	}
....
}

The applicationContext.xml for Spring:

...
<bean id="myFile" class="java.io.File">
    <constructor-arg>
        <value>${file.path}</value>
    </constructor-arg>
</bean>
...

In the properties file, the $file.path is defined as file.path=D:\data\test\my-spring-file.txt.

When I trying to run the java code, it returns me

Exception in thread "main" java.lang.IllegalArgumentException: Malformed \uxxxx encoding.
at java.util.Properties.loadConvert(Unknown Source)
at java.util.Properties.load(Unknown Source)
....

So, I change the $file.path to file.path=D:\\data\\test\\my-spring-file.txt, and its work fine to me!

Written by Alfred

November 13, 2008 at 15:20

Posted in Java, Spring

Tagged with , ,

Java Output Formatting

leave a comment »

Here are some often used java output formatting with using String formatter..

// format string output
System.out.println(String.format("String  [%s]", "a string"));
/* $> String  [a string] */

// format integer output
System.out.println(String.format("Integer [%d]", 12345));
/* $> Integer [12345] */

// format double output
System.out.println(String.format("Double  [%.2f]", 123.456d));
/* $> Double  [123.46] */

// format floating point output
System.out.println(String.format("Float   [%.3f]", 0.123f));
/* $> Float   [0.123] */

// format boolean output
System.out.println(String.format("Boolean [%b]", true));
/* $> Boolean [true] */

// format date output
System.out.println(String.format(
"SimpleDateFormat-1 [%s]", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())));
/* $> SimpleDateFormat-1 [2008-10-20 14:36:50.234] */

// format date output
System.out.println(String.format(
"SimpleDateFormat-2 [%s]", new SimpleDateFormat("yyMMdd_HHmmss").format(new Date())));
/* $> SimpleDateFormat-2 [081020_143650] */

Written by Alfred

October 20, 2008 at 14:44

Posted in Java

Tagged with ,

Class vs Object vs Instance

with 9 comments

In OO Programming, we often hear of terms like “Class”, “Object” and “Instance”; but what actually is a Class / Object / Instance?

In short, An object is a software bundle of related state and behavior. A class is a blueprint or prototype from which objects are created. An instance is a single and unique unit of a class.

Example, we have a blueprint (class) represents student (object) with fields like name, age, course (class member). And we have 2 students here, Foo and Bob. So, Foo and Bob is 2 different instances of the class (Student class) that represent object (Student people).

Let me go into details…

Object
Real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and state (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.

Class
Class is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.

Instance
An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

Written by Alfred

July 8, 2008 at 13:49

Posted in Java

Tagged with

No Hibernate Session bound to thread

with one comment

Problem:
I hit an error “No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here” while I’m doing unit testing in an application that combining Spring Batch and Hibernate. This problem exists when I try to do some data insertion at the Spring Batch Listener.

Solution:
The root of this problem occurred is because there is NO hibernate session at the Spring Batch Listener level. How come?!?! Its because the AOP pointcut I defined and use throughout the application is at the Batch JobRepository
<aop:config>
<aop:advisor pointcut="execution(* org.springframework.batch.core..*Repository+.*(..))"
advice-ref="txAdvice" />
</aop:config>

But the Batch Listener is not under the same / child package of the JobRepository. The Listener is under org.springframework.batch.core.StepExecutionListener. To ease the configuration, I add in another pointcut at my business package my.com.company.project.writer.MyItemWriter.beforeStep.
The AOP pointcut I added is:
<aop:config>
<aop:advisor pointcut="execution(* my.com.pv.batch.report.writer.CdrItemWriter.beforeStep(..))"
advice-ref="txAdvice" />
</aop:config>

Lessons Learned:
1. Identified where is the point cuts, is that the existing pointcut is enough for me?

Written by Alfred

April 23, 2008 at 10:40

Posted in Java

Tagged with , , ,