본문 바로가기
Java

object to .class

by 자바초보자 2016. 8. 25.
728x90

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Service;

import javassist.CannotCompileException;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

@Service
public class ClazzToFile {

 public void strat( Class clazz ){
  System.out.println("S =============== ClazzToFile ==================");
 
  try {
   ClassPool pool = ClassPool.getDefault();
   //ClassPool pool = new ClassPool(true);
   System.out.println("pool111 222222: " + pool);
   
   pool.insertClassPath(new ClassClassPath(clazz));
   
   System.out.println("clazz.getName() : " + clazz.getName());
   CtClass cc = pool.get(clazz.getName());
   System.out.println("cc : " + cc);
   if(cc != null){
    CtMethod[] allDeclaredMethods = cc.getDeclaredMethods();
    System.out.println(clazz.getName() + " has : " + allDeclaredMethods.length + " methods ");
    
    byte[] code = cc.toBytecode();
    System.out.println("code : " + code);
    if(code != null && code.length > 0){
     System.out.println("code.length : " + code.length);
     File file = new File("c:/tmp/"+clazz.getName()+".class");
     file.createNewFile();
     FileOutputStream fos = new FileOutputStream(file);
     fos.write(code);
     fos.close();
     System.out.println("file write !!!");
    }
   }
  } catch (NotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (CannotCompileException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  System.out.println("E =============== ClazzToFile ==================");
 
 }
}

 

-------------------------------------------------------------------------------------------------------------------

classloader 변경 시 class 들을 맵에 담아둠...

 

System.out.println("=============== TestInterceptor =====================");
  //new ClazzToFile().strat(SiteUserController.class);
  //new ClazzToFile().strat(SiteUserController.class);
  
  HashMap<String, Class<?>> maps = customClassLoader.getMapClasses();
  if(maps != null && maps.size() > 0){
   for(String key : maps.keySet()){
    System.out.println("== key : " + key);
    new ClazzToFile().strat(maps.get(key));
   }
  }
  
  System.out.println("=============== TestInterceptor =====================");

 

728x90

'Java' 카테고리의 다른 글

unirest https url 적용  (0) 2022.06.14
mssql 컬럼추가  (0) 2020.05.11
한글 인코딩 테스트 인코딩 변환  (0) 2016.08.12
list 재정렬  (0) 2016.08.10
개발 참고  (0) 2016.07.05