Friday, December 16, 2011

Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();

Java - getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();


A relatively simple concept that confuses many java beginners!


Java Code:

String path = getClass().getClassLoader().getResource("myfolder/data/file.txt").getPath();



This code will try to get exact path of foldermyfolder/data/file.txt”.

The parent folder of this folder “myfolder/data/file.txt” should be mentioned in class path.


e.g. If the exact path of this folder is “C:/properties/myfolder/data/file.txt”; path “C:/properties” should be mentioned in classpath of the application (build-path in eclipse). When the above mentioned code is executed in application, it returns the exact path of the folder location and assigns it to ‘path’ variable.


Hence after execution of this code, ‘path’ variable will contain value “C:/properties/myfolder/data/file.txt”.


If we change root location of the application or we change folder structure of the parent folder of “myfolder/data/file.txt“, we will need to change only classpath.

This avoids hard-coding of the absolute path in source code. (Important for portability of application across windows and unix platforms.)



Monday, December 5, 2011

Hibernate: wrong usage of merge()

Note the wrong usage of merge():

merge() doesn't make the object passed into it persistent, it returns another instance with the same state instead,

So you should write: bean.setManufacturer(s.merge(bean.getManufacturer()));