vendredi 8 juillet 2016

Access a class's fields with Java reflection

I'm trying to access a document class that has id, name, text and list of words. I try to compare id which I have with the ids and when found get the list of words to find some word. I was trying with java reflection but I'm unable to get it working? Any help is highly appreciated.

public class Doc {

private static int documentID;
private static Doc docInstance = null;
private String documentName;
private String documentText;
private ArrayList<String> listOfTokens;
static int docCount = 0;

public Doc(){
    documentID = 0;
    listOfTokens = new ArrayList<String>();
    tokFreq = 0;
    docCount++;
}

public static Doc getDocInstance(){ 
    if (docInstance == null) {
        docInstance = new Doc();
    }
    return docInstance;
}

----------etc

so I'm trying to do this..

         Class docOb = Doc.class;
         Field[] fields = docOb.getDeclaredFields();

         for (Field field : fields) {
             field.setAccessible(true);
             if (field.get("documentID")== LL){
                 String[] docIdTokens = (String[]) field.get("listOfTokens");
                 for (String s : docIdTokens){
                     if(s.equalsIgnoreCase(key)){
                         termFrequency++;
                     }

                 }break;
             }

         }

Aucun commentaire:

Enregistrer un commentaire