Can you override Static Methods in Java?
Question: Can you override Static Methods in Java?
Answer: Well... the answer is NO if you think from the perspective of how an overriden method should behave in Java. But, you don't get any compiler error if you try to override a static method. That means, if you try to override, Java doesn't stop you doing that; but you certainly don't get the same effect as you get for non-static methods. Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... any guesses for the reason why do they behave strangely? Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information. Accessing them using object references is just an extra liberty given by the designers of Java and we should certainly not think of stopping that practice only when they restrict it :-)
Example: let's try to see what happens if we try overriding a static method:-
class SuperClass{
......
public static void staticMethod(){
System.out.println("SuperClass: inside staticMethod");
}
......
}
public class SubClass extends SuperClass{
......
//overriding the static method
public static void staticMethod(){
System.out.println("SubClass: inside staticMethod");
}
......
public static void main(String []args){
......
SuperClass superClassWithSuperCons = new SuperClass();
SuperClass superClassWithSubCons = new SubClass();
SubClass subClassWithSubCons = new SubClass();
superClassWithSuperCons.staticMethod();
superClassWithSubCons.staticMethod();
subClassWithSubCons.staticMethod();
...
}
}
Output:-
SuperClass: inside staticMethod
SuperClass: inside staticMethod
SubClass: inside staticMethod
Notice the second line of the output. Had the staticMethod been overriden this line should have been identical to the third line as we're invoking the 'staticMethod()' on an object of Runtime Type as 'SubClass' and not as 'SuperClass'. This confirms that the static methods are always resolved using their compile time type information only.
Search Blog
Sunday, January 15, 2012
Overriding Static Methods
Taken from http://geekexplains.blogspot.com/2008/06/can-you-override-static-methods-in-java.html
For Singleton Pattern
Java Singleton Pattern ( One Of Creational Patterns ) icin:
1) Bir class'in icinde Private Static Object
2) Private Constructor
3) Static get Instance Method of the object
4) Change getInstance Method to synchronized for threadsafe
5) Override clone method of Object, and do
throw new CloneNotSupportedException()
6) Optional, making the class final to not override
Tuesday, January 10, 2012
Google Searchbox
Search calismadigi icin, google search koydum.
design - add new gadget
html/javascript
<form method="get" action="http://www.google.com/search">
<div style="border:1px solid black;padding:4px;width:20em;">
<table border="0" cellpadding="0">
<tr><td>
<input type="text" name="q" size="30"
maxlength="270" value="" />
<input type="submit" value="Google Search" /></td></tr>
<tr><td align="center" style="font-size:75%">
<input type="checkbox" name="sitesearch"
value="pclives.blogspot.com" checked /> Search Pclives.blogspot.com<br />
</td></tr></table>
</div>
</form>
AOP 2
AOP in Spring
Advice: Method Names
Pointcut: Advice path lere shortcut
JoinPoint: Aspect de called method un ismini verir. Aspect metoduna parametre
olarak yazilir.
<aop:aspectj-autoproxy /> bunu spring.xml e yazmak lazim.
Spring de member variable update icin advice yazilmaz.
sadece method icin yaziliyor. member variable icin sadece aspectj kullanmak lazim
@Before("execution(public void String getName())")
Bu anotation sadece bu metodlarda calisir.
joinPoint.getTarget() dersen cagiran object i gosterir
joinPoint.toString() dersen cagiran metodu yazar.
joinPoint.getTarget() ile , objeyi cekip islem yapabilirsin
@Before("args(String)")
argument i String olan metodlardan once calistir.
@Before("args(name)")
public void xxAdvice(String name) {
}
Burada name olarak value yu kullanabiliriz. Bunun da String olmasi lazim.
@Before annotation'i, biz explicit olarak metodu cagirdigimiz zaman
calisir. Spring initialize olurken bu metodu cagirdigi zaman calismaz.
( Spring initialize olurken, default value leri set ediyordu ya )
@After
Bu annotation i metoddan sonra calismasi icin yapabilirsin.
@AfterReturning
Bu annotation ile advice sadece return olunca yani exception olmazsa
cagirilir.
@AfterThrowing
Sadece throw olduktan sonra cagirilir.
Aspect class larinin annotation'i @Aspect
@AfterReturning(pointcut="args(name)",returning="returnString")
public void xxadvice(String name,String returnString){
}
return String i almak icin bu annotation i kullanabiliriz.
Advice metodlarina parametre olarak Object verirsek, cast ederek
istedigimiz objeye cevirebiliriz.
@AfterThrowing(pointcut="args(name)",throwing="ex")
public void xxxAdvice(String name, RuntimeException ex)
Bu sekilde ise exception i alabiliriz.
Ayni parametre olarak Object verdiğimiz gibi, throwing olarak Exception
class ini veririsek cast ederek istedigimizi alabiliriz.
@Around annotation i ile hem before hem after'da calistirabilirsin
advice'i.
@Around("test()")
public void xxAdvice(ProceedingJoinPoint proceedingJoinPoint) {
//before da cagirilacak yer
proceedingJoinPoint.proceed(); //metodun gercekten cagirilmasi
//after da cagirilacak yer.
}
Fakat around yaptigimiz zaman ProceedingJoinPoint kullanmak lazim. Ve bu sart !
Ikisini tek yerde yapabiliriz.
Neden hep @Around hep kullanmiyoruz, hep en kolay olani kullanmak lazim.
Always the least powerful
Eger eger advice olan metod obje donuyorsa, @Around metod da obje donmeli
Tipik conventionlar
pakeler asagidaki gibi:
com.xx : main
com.xx.aspect : aspectler icin . Class isimleri XXXAspect
com.xx.model : bean ler icin
com.xx.service : servisler icin ( servislerden bean leri cagirma ) . XXXService
Conventionlarimiz olursa gerek class ismi, gerek servis ismi, aspect lerde
pointcut expression yazarken cok kolay olur. Cunku pointcut expression lar
da regular expression gibi.
expression lari && ile baglayabilirsin
@Before("a" && "b")
Yeni bir annotation yaratirsin. xxxAnnotation
@Around("@annotation(com.xx.xxxAnnotation)")
dersin. Sonra advice istedigin metodun ustune gelip @xxxAnnotation dersin.
Sadece o annotation in bulundugu metodlari cagirir.
Annotation yerine, spring xml in icine de aspect leri tanimlayabiliriz.
<aop:config>
<aop:aspect id="xx" ref="beanIsmi">
<aop:pointcut id="allGetters" expression="execution("* get())"/>
<aop:around method="xxx" pointcut-ref="allGetters"/>
</aop:aspect> // bu aslinda class'a @Aspect tanimlamak ile ayni
</aop:config>
Aspect Class inin da bean xml icinde tanimlanmis olmasi lazim bunu tabi unutmamak lazim.
annotated ve xml solution icin de.
Annotation genelde functionality acisindan, XML configuration acisindan tercih edilir.
Mesela transaction tanimlama functionality dir, debug mod ya da degil flag i mesela
xml configuration dir.
Sunday, November 27, 2011
Redmine Installation to Windows
Installation
1) redmine indir siteden 1.2.2 indir.
2) mysqld indir.
3) config/database.yml.example i database.yml olarak kopyala ayni yere.
4) http://rubyinstaller.org/downloads/archives a gidin rubyinstaller for windows indir. 1.8.7 indirecegiz.
5) C:\Ruby187\bin i PATH'e koy.
5) install ederken add ruby executables to PATH isaretle, associate with files isaretle
6) create database redmine character set utf8; create user redmine@localhost identified by 'redmine'; grant all privileges on redmine.* to 'redmine'@'localhost';
7)
7) http://rubyforge.org/frs/?group_id=126 rubygems 1.8.11.zip indir. Rubygems ruby nin package manageri
8) D:\redmine\rubygems-1.8.11\rubygems-1.8.11 de setup.rb'ye tikla. 5) te associate edersen direkt tiklayinca calisir.
7) gem install rails -v=2.3.11 de
8) gem install rack -v=1.1.1
9) gem install -v=0.4.2 i18n
10) rake db:migrate RAILS_NEW="production" de redmine root directory de hata aldi
11) rubygems yuksek version kaldi. "gem update --system 1.6.2" de
12) rake generate_session_store
13) SET RAILS_ENV=production rake db:migrate gem mysql son version degil dedi
14) gem install mysql
15) tam yuklemedi, library eksik buldu. http://instantrails.rubyforge.org/svn/trunk/InstantRails-win/InstantRails/mysql/bin/libmySQL.dll
16) indirdim. ruby/bin directory sine kopyaliyorum.
17) ne olur ne olmaz tekrar gem install mysql dedim.
18) tekrar rake db:migrate dedim.
19) simdi bu : rake redmine:load_default_data her zaman SET RAILS_ENV=production yaptigimiz command prompt ta oldugumuza dikkat edelim. language olarak "en" sec.
20) Simdi ruby script/server webrick -e production yap
21) sonra webde http://localhost:3000/ de
22) admin:admin ile login ol.
23) email icin config/configuration.yml.example i configuration.yml yap.
24) ms exchange in de delivery method'u smtp dir.
25) ms exchange smtp icin authentication istemez. Bu yuzden domain authentication username password u
commentle.
26) restart et. Her configuration degisikliginden sonra restart etmeyi unutmuyorsun.
27) admin sifreni degistir.
28) settings/email notifications dan emission email address i redmine@CEBUA yap. Email adresi olmasi lazim yoksa kabul etmiyor.
29) Administration/Settings/General icinde Host Name and Path bolumunu gercek hostname ile degistir. Bu bolum emaillerde geliyor.
30) Administration/Settings/Email Notifications bolumunde emails footer da host u da degistir.
31) Ldap authentication yazarken.
Wednesday, October 5, 2011
Mozilla Firefox Downgrade From 7 To 6
1. Visit Firefox releases folder located in Mozilla FTP Server directory in your browser.
ftp://ftp.mozilla.org/pub/mozilla.org/firefox/releases/
2. Open 6.0.2>Win32>en-US and download Firefox 6.0.2 set up file from there and install it over Firefox 7 in your Computer.
3. You’ll be automatically downgraded to Firefox 6.0.2 without loosing any settings or extensions.
Sunday, January 9, 2011
Ibatis Dynamic SQL
This is a feature available in iBatis but it is not mentioned in the documentation. You can find the example in the iBatis source code under the unit tests.
Let’s said I need to run the following SQL statement
select * from my_table where col_1 in ('1','2','3')
So how do I pass in the values of 1, 2 and 3 ?
In this case you need to pass in a list parameter. The correct iBatis syntax should be
<select id="select-test" resultMap="MyTableResult"
parameterClass="list">
select * from my_table where col_1 in
<iterate open="(" close=")" conjunction=",">
#[]#
</iterate>
</select>
And in Java you should pass in a java.util.List. E.g.
List<String> list = new ArrayList<String>(3);
list.add("1");
list.add("2");
list.add("3");
List objs = sqlMapClient.queryForList("select-test",list);
This is another example
<select id="getProducts" parameterClass="Product"
resultClass="Product">
SELECT * FROM Products
<dynamic prepend="WHERE productType IN ">
<iterate property="productTypes"
open="(" close=")"
conjunction=",">
productType=#productType#
</iterate>
</dynamic>
</select>
…
Subscribe to:
Posts (Atom)