2017-05-01 10 views

答えて

0

、あなただけの自分フィールド創造に直接初期化を追加することができます。

jc.field(JMod.PRIVATE, HashMap.class, "initAttributes") 
    .init(JExpr._new(codeModel.ref(HashMap.class))); 

さらにいくつかのヒント:

  • をあなたがすべきことを考えると、通常program to an interfaceの場合、「できるだけ基本的な」型を使用して変数を宣言することをお勧めします。 Mapがここに関連するインタフェースであるので、あなたはほとんどこれまでは、基本的には、常にのみ

    private Map map; 
    

    として

    private HashMap map; 
    

    として変数を宣言していないが、必要があります。

  • ジェネリックをJCodeModelに追加することもできます。これらは通常、特定の種類の電話をnarrowに呼び出す場合があります。もう少し努力しますが、生の型のために警告を出さずにコンパイルできるコードを生成します。

例を示します。

package com.example; 

import java.util.HashMap; 
import java.util.Map; 

public class Example { 

    private Map<String, Integer> initAttributes = new HashMap<String, Integer>(); 

} 
次のように生成されたクラスは見え

import java.util.HashMap; 
import java.util.Map; 

import com.sun.codemodel.CodeWriter; 
import com.sun.codemodel.JClass; 
import com.sun.codemodel.JCodeModel; 
import com.sun.codemodel.JDefinedClass; 
import com.sun.codemodel.JExpr; 
import com.sun.codemodel.JMod; 
import com.sun.codemodel.writer.SingleStreamCodeWriter; 

public class InitializeFieldInCodeModel 
{ 
    public static void main(String[] args) throws Exception 
    { 
     JCodeModel codeModel = new JCodeModel(); 
     JDefinedClass definedClass = codeModel._class("com.example.Example"); 

     JClass keyType = codeModel.ref(String.class); 
     JClass valueType = codeModel.ref(Integer.class); 
     JClass mapClass = 
      codeModel.ref(Map.class).narrow(keyType, valueType); 
     JClass hashMapClass = 
      codeModel.ref(HashMap.class).narrow(keyType, valueType); 
     definedClass.field(JMod.PRIVATE, mapClass, "initAttributes") 
      .init(JExpr._new(hashMapClass)); 

     CodeWriter codeWriter = new SingleStreamCodeWriter(System.out); 
     codeModel.build(codeWriter); 
    } 

} 

(。それは、あなたがそれに応じてこれを調整することができるマップの値型とキータイプとIntegerとしてStringを使用しています)

関連する問題