The original reason for my Jaxb Question
JaxB reference resolving
was that I couldn't get the same issue working with the simple-framework:
http://old.nabble.com/Two-Phase-support-for-CycleStrategy--td34802791.html
Today I got the things working with a persister call back to the same point as in my Jaxb Questions:
I get copies - not references. Again I am looking for a solution with proper references. This time for the Simple XML framework.
The example here has the base class "ModelElement" not Person as in the other question. Otherwise the problem is the same.
Again I am calling the unmarshalling twice to get all ids in PASS 1 and use the gathered results from the lookup HashMap created in PASS2.
What would be a solution to get proper references? My assumption is that adding a call back that actually lets the called function modify the unmarshalling result (see How to use an output parameter in Java? for a wrapping approach)
would do the trick (comparable to the JaxB solution I have posted in the meantime).
Persister serializer = new Persister();
ModelElementSimpleXmlImpl.lookup.clear();
serializer.read(result, xml);
System.err.println("PASS 2");
serializer.read(result, xml);
This code is from the ModelElementSimpleXmlImpl base class:
...
protected String ref;
/**
* getter for xsd:string/String id
* #return id
*/
#org.simpleframework.xml.Attribute(name="ref",required=false)
public String getRef() {
return ref;
}
/**
* setter for xsd:string/String id
* #param pid - new value for id
*/
#org.simpleframework.xml.Attribute(name="ref",required=false)
public void setRef(String pRef) {
ref=pRef;
}
private boolean debug=true;
/**
* show debug information
* #param title
* #param key
* #param me
* #param found
*/
public void showDebug(String title,String key,ModelElementSimpleXmlImpl me, ModelElementSimpleXmlImpl found) {
String deref="?";
if (found!=null)
deref="->"+found.getId()+"("+found.getClass().getSimpleName()+")";
if (debug)
System.err.println(title+": "+key+"("+me.getClass().getSimpleName()+")"+deref+" - "+this);
}
/**
* keep track of the elements already seen
*/
public static Map<String,ModelElementSimpleXmlImpl> lookup=new HashMap<String,ModelElementSimpleXmlImpl>();
#Validate
public void validate() {
ModelElementSimpleXmlImpl me=this;
String key=me.getId();
if (key!=null) {
showDebug("id",key,me,null);
lookup.put(key, me);
}
key=me.getRef();
if (key!=null) {
if (lookup.containsKey(key)) {
ModelElementSimpleXmlImpl meRef=lookup.get(key);
showDebug("ref",key,me,meRef);
me.setRef(null);
me.copyFrom(meRef);
} else {
if (debug)
showDebug("ref",me.getRef(),me,null);
}
}
}
Niall Gallagher suggested:
Should be fairly easy to do with something like the CycleStrategy. Just create MyCycleStrategy and where there is an exception with "Invalid reference" just return null and remember the reference. When you have picked up all the ids and the values then do a second pass. In the second pass assign the value to the first occurrence of either the ref or the id. Then all following references should be given the same value. This should work.
And he is right. The following extended Cycle Strategy works as proposed:
/**
* Two Path Cycle Strategy
*
* #author wf
*
*/
public static class TwoPathCycleStrategy extends CycleStrategy {
String id;
String ref;
public static boolean debug = false;
/**
* create a twoPath Cycle Strategy
*
* #param id
* #param ref
*/
public TwoPathCycleStrategy(String id, String ref) {
super(id, ref);
this.id = id;
this.ref = ref;
}
/**
* show debug information
*
* #param title
* #param key
* #param value
*/
public void showDebug(String title, String key, Value value) {
if (debug) {
String id = "?";
Object v = value;
while ((v instanceof Value) && ((Value) v).isReference()) {
v = ((Value) v).getValue();
}
if (v == null) {
id = "null";
} else {
// FIXME - adapt to your code or comment out
//if (v instanceof ModelElement) {
// ModelElement me = (ModelElement) v;
// id = me.getId();
//}
}
System.err.println(title + ":" + key + "->"
+ v.getClass().getSimpleName() + ":"
+ value.getType().getSimpleName() + ":" + value.isReference() + ":"
+ id);
}
}
public Map<String, Value> lookup = new HashMap<String, Value>();
#SuppressWarnings("rawtypes")
#Override
public Value read(Type type, NodeMap node, Map map) throws Exception {
Value value = null;
Node refNode = node.get(ref);
Node keyNode = node.get(id);
try {
value = super.read(type, node, map);
if (keyNode != null) {
String key = keyNode.getValue();
if (value != null) {
showDebug("id", key, value);
lookup.put(key, value);
} else {
showDebug("id?", key, value);
}
}
} catch (CycleException ce) {
if (ce.getMessage().contains("Invalid reference")) {
if (refNode != null) {
String key = refNode.getValue();
if (lookup.containsKey(key)) {
value = lookup.get(key);
showDebug("ref", key, value);
} else {
showDebug("ref?",key,null);
}
}
} else {
throw ce;
}
}
return value;
}
}
Related
For a project, which generates XML-files based on a XSD-file, I want to automatically generate the documentation. *
In this documentation I list the different elements defined in the XSD.
And for each element I want to show an example of that element.
The problem is, that the XML-example might be quite long and contains a lot of children.
Therefore I want to shorten the example by:
limiting the shown depth
limiting the amount of elements in a list
For the root-element that example might look like the following:
<root>
<elements>
<element>...<element>
<element>...<element>
<element>...<element>
...
</elements>
</root>
My approach:
To generate classes from the XSD and to generate and validate the XML files I use JAXB.
But I could not figure out how to marshal a Non-Root element.
Therefore I am generating my examples with XStream.
To limit the XML-example I am trying to decorate the PrettyPrintWriter, but that seems to be quite cumbersome.
The two decorators can be seen in my answer.
I just did not expect to care about the internals of a library for such a (common?) feature.
Is there an easier way to do this? (I can also use another library than XStream, or none at all.)
*
My approach is influenced by Spring Auto Rest Docs
To limit the shown depth I created the following XStream WriterWrapper. The class can wrap for example a PrettyPrintWriter and ensures that the wrapped writer only receives the nodes above a given depth threshold.
public class RestrictedPrettyPrintWriter extends WriterWrapper {
private final ConverterLookup converterLookup;
private final int maximalDepth;
private int depth;
public RestrictedPrettyPrintWriter(HierarchicalStreamWriter sw, ConverterLookup converterLookup, int maximalDepth) {
super(sw);
this.converterLookup = converterLookup;
this.maximalDepth = maximalDepth;
}
#Override public void startNode(String name, Class clazz) {
Converter converter = this.converterLookup.lookupConverterForType(clazz);
boolean isSimpleType = converter instanceof SingleValueConverter;
_startNode(name, !isSimpleType);
}
#Override public void startNode(String name) {
_startNode(name, false);
}
#Override public void endNode() {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.endNode();
}
depth--;
}
#Override public void addAttribute(String key, String value) {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.addAttribute(key, value);
}
}
#Override public void setValue(String text) {
if (_isLessDeepThanMaximalDepth() || _isMaximalDepthReached()) {
super.setValue(text);
}
}
/**
* #param name name of the new node
* #param isComplexType indicates if the element is complex or contains a single value
*/
private void _startNode(String name, boolean isComplexType) {
depth++;
if (_isLessDeepThanMaximalDepth()) {
super.startNode(name);
} else if (_isMaximalDepthReached()) {
super.startNode(name);
/*
* set the placeholder value now
* setValue() will never be called for complex types
*/
if (isComplexType) {
super.setValue("...");
}
}
}
private boolean _isMaximalDepthReached() {
return depth == maximalDepth;
}
private boolean _isLessDeepThanMaximalDepth() {
return depth < maximalDepth;
}
}
To limit the lists, I tried, in a first attempt, to modify the XStream CollectionConverter. But this approach was not general enough because implicit lists do not use this converter.
Therefore I created another WriterWrapper which counts the consecutive occurrences of elements with the same name.
public class RestrictedCollectionWriter extends WriterWrapper {
private final int maxConsecutiveOccurences;
private int depth;
/** Contains one element per depth.
* More precisely: the current element and its parents.
*/
private Map < Integer, Elements > elements = new HashMap < > ();
public RestrictedCollectionWriter(HierarchicalStreamWriter sw, int maxConsecutiveOccurences) {
super(sw);
this.maxConsecutiveOccurences = maxConsecutiveOccurences;
}
#Override public void startNode(String name, Class clazz) {
_startNode(name);
}
#Override public void startNode(String name) {
_startNode(name);
}
#Override public void endNode() {
if (_isCurrentElementPrintable()) {
super.endNode();
}
depth--;
}
#Override public void addAttribute(String key, String value) {
if (_isCurrentElementPrintable()) {
super.addAttribute(key, value);
}
}
#Override public void setValue(String text) {
if (_isCurrentElementPrintable()) {
super.setValue(text);
}
}
/**
* #param name name of the new node
*/
private void _startNode(String name) {
depth++;
Elements currentElement = this.elements.getOrDefault(depth, new Elements());
this.elements.put(depth, currentElement);
Elements parent = this.elements.get(depth - 1);
boolean parentPrintable = parent == null ? true : parent.isPrintable();
currentElement.setName(name, parentPrintable);
if (currentElement.isPrintable()) {
super.startNode(name);
}
}
private boolean _isCurrentElementPrintable() {
Elements currentElement = this.elements.get(depth);
return currentElement.isPrintable();
}
/**
* Evaluates if an element is printable or not.
* This is based on the concurrent occurences of the element's name
* and if the parent element is printable or not.
*/
private class Elements {
private String name = "";
private int concurrentOccurences = 0;
private boolean parentPrintable;
public void setName(String name, boolean parentPrintable) {
if (this.name.equals(name)) {
concurrentOccurences++;
} else {
concurrentOccurences = 1;
}
this.name = name;
this.parentPrintable = parentPrintable;
}
public boolean isPrintable() {
return parentPrintable && concurrentOccurences <= maxConsecutiveOccurences;
}
}
}
The following listing shows, how the two classes can be used.
XStream xstream = new XStream(new StaxDriver());
StringWriter sw = new StringWriter();
PrettyPrintWriter pw = new PrettyPrintWriter(sw);
RestrictedCollectionWriter cw = new RestrictedCollectionWriter(pw, 3);
xstream.marshal(objectToMarshal, new RestrictedPrettyPrintWriter(cw, xstream.getConverterLookup(), 3));
I have below table
question_text_id question_id language_id question_text
2 7 1 english_text_1
3 7 2 spanish_text_1
4 8 2 spanish_text_2
5 8 1 english_text_2
NOw i want to create list for each distinct question_id
i have used below code
List<QuestionText> questionTextList = questionManager.getQuestionsTextByQuestionId(Long.parseLong(questions.getQuestionId().toString()));
for (QuestionText questionText : questionTextList) {
questionMap.put("questionId", questionText.getQuestionId());
questionMap.put("language", questionText.getLanguageId());
if(questionText.getLanguageId().longValue() == 1){
questionMap.put("englishQuestionText",questionText.getQuestionText());
} else {
questionMap.put("spanishQuestionText",questionText.getQuestionText());
}
questionListMap.add(questionMap);
}
adminCollectionBookendModel.put("questionListMap",questionListMap);
[{questionId = 1,language=1, englishQuestionText = english_text_1,spanishQuestionText=spanish_text_1},{questionId = 1,language=2, englishQuestionText = english_text_1,spanishQuestionText=spanish_text_1}]
But this give me repeatetion of object of same data if i have both spanish and english question text as shown above. How to get unique list?
How to get both spanish text and english text for each question_id along with language_id and to access it?
Please help me on this
The first step would be to create a POJO Class like this,
public class QuestionDetails {
private int questionId;
private int englishLanguageId;
private int spanishLanguageId;
private String englishLanguageText;
private String spanishLanguageText;
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public int getEnglishLanguageId() {
return englishLanguageId;
}
public void setEnglishLanguageId(int englishLanguageId) {
this.englishLanguageId = englishLanguageId;
}
public int getSpanishLanguageId() {
return spanishLanguageId;
}
public void setSpanishLanguageId(int spanishLanguageId) {
this.spanishLanguageId = spanishLanguageId;
}
public String getEnglishLanguageText() {
return englishLanguageText;
}
public void setEnglishLanguageText(String englishLanguageText) {
this.englishLanguageText = englishLanguageText;
}
public String getSpanishLanguageText() {
return spanishLanguageText;
}
public void setSpanishLanguageText(String spanishLanguageText) {
this.spanishLanguageText = spanishLanguageText;
}
#Override
public String toString() {
return new StringBuilder().append("questionId: ").append(questionId)
.append(" ,englishLanguageId: ").append(englishLanguageId)
.append(" ,englishLanguageText: ").append(englishLanguageText)
.append(" ,spanishLanguageId: ").append(spanishLanguageId)
.append(" ,spanishLanguageText: ").append(spanishLanguageText)
.toString();
}
}
Next step would be to change your code snippet like this:
List<QuestionDetails> questionsList = new ArrayList<>();
List<QuestionText> questionTextList = questionManager
.getQuestionsTextByQuestionId(Long.parseLong(questions
.getQuestionId().toString()));
for (QuestionText questionText : questionTextList) {
/* Get QuestionDetails Object */
QuestionDetails qd = getQuestionDetails(
questionText.getQuestionId(), questionsList);
/* Check Null */
if(null == qd) {
/* Get New Object */
qd = new QuestionDetails();
/* Add Object To List */
questionsList.add(qd);
}
/* Set Question ID */
qd.setQuestionId(questionText.getQuestionId());
/* Set Language ID & Text */
if (questionText.getLanguageId().longValue() == 1) {
qd.setEnglishLanguageId(questionText.getLanguageId()
.longValue());
qd.setEnglishLanguageText(questionText.getQuestionText());
} else {
qd.setSpanishLanguageId(questionText.getLanguageId()
.longValue());
qd.setSpanishLanguageText(questionText.getQuestionText());
}
}
adminCollectionBookendModel.put("questionListMap", questionsList);
Finally, here is the implementation of the getQuestionDetails function:
private QuestionDetails getQuestionDetails(int questionId,
List<QuestionDetails> questionsList) {
/* Search Existing Object */
for (QuestionDetails qd : questionsList) {
/* Match Found */
if (qd.getQuestionId() == questionId) {
return qd;
}
}
/* No Object Found */
return null;
}
I would recommend doing the following:
To distinguish QuestionText, you need to override equals method using question_text_id. Otherwise two questions with the same question_id, but different language texts would be equal.
Then create two separate maps for each language. Then just iterate throug all questions and put each question in a corresponding map by question_id. You can retrive a question object by its question_id and get all necessary fields from it, including spanish / english text
List<QuestionText> questionTextList = questionManager.getQuestionsTextByQuestionId(Long.parseLong(questions.getQuestionTextId().toString()));
for (QuestionText questionText : questionTextList) {
if(questionText.getLanguageId().longValue() == 1){
englishQuestionMap.put("question_id",questionText);
} else {
spanishQuestionMap.put("question_id",questionText);
}
questionListMap.add(questionMap);
}
So, your maps will have type of Map<Long, QuestionText>
This is my first time asking on this site, and got my exam tomorrow so trying to make my code great! I will link the whole class (Even though its 3 others).
This is the method, and I cant manage to remove an object from lagerplass, adding it to hk.addVarer works tho. The idea behind all this is that lagerplass is were the items is stored in a store(butikk), so when people buy an item from the store and put it in handlekurv the items gets removed from the storage(lagerplass) :
public void leggTilHandlekurv(String varenavn)
{
for (Varer a : lagerplass)
{
if (a.getVarenavn().equals(varenavn))
{
hk.addVarer(a);
lagerplass.remove(varenavn);
}
}
}
Here is the kode for the whole Butikk class
public class Butikk
{
// instance variables - replace the example below with your own
public ArrayList<Varer> lagerplass;
Handlekurv hk = new Handlekurv();
/**
* Constructor for objects of class Butikk
*/
public Butikk()
{
// initialise instance variables
lagerplass = new ArrayList<Varer>();
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void nyHeadset(String lyd, String vare,int pris, String varenavn )
{
// put your code here
Headset nyHeadset = new Headset ( lyd, vare, pris, varenavn);
lagerplass.add(nyHeadset);
}
public void nyMus(String vare, int pris, String varenavn, int dpi)
{
Mus nyMus = new Mus(vare, pris, varenavn, dpi);
lagerplass.add(nyMus);
}
public void printLagerplass()
{
for (Varer vare : lagerplass)
{
vare.printDetails();
}
}
public int lagerplassSize()
{
return lagerplass.size();
}
public void fjernHeleLagerplass()
{
lagerplass.clear();
}
public void leggTilHandlekurv(String varenavn)
{
Iterator<Varer> iterator = lagerplass.iterator();
while(iterator.hasNext()) {
Varer a = iterator.next();
if (a.getVarenavn().equals(varenavn)) {
iterator.remove();
hk.addVarer(a);
}
}
}
public void printHeleHandlekurven()
{
hk.printHandlekurv();
}
}enter code here
Here is the kode for the whole Varer class
enter code here
public class Varer
{
// Representerer merke og pris til en vare.
private String vare;
private String merke;
private int pris;
private String varenavn;
/**
* Constructor for klassen Varer
*/
public Varer(int pris, String varenavn, String vare)
{
merke = "Razor";
this.pris = pris;
this.varenavn = varenavn;
this.vare = vare;
}
public String getMerke()
{
return merke;
}
public int getPris()
{
return pris;
}
public String getVarenavn()
{
return varenavn;
}
public String getVare()
{
return vare;
}
public String getDetails()
{
return vare + ", " + merke +" " + varenavn + ", "+pris + " kr.";
}
public void printDetails()
{
System.out.println(vare + ", " + merke +" "+ varenavn + ", "+pris + " kr.");
System.out.println();
}
Removing an item from a collection while iterating over it should yield a ConcurrentModificationException, which I presume is what you are getting and is why you cannot remove from it.
To remove an element while iterating over a collection, you will need to get that collection's iterator and remove it through the collection's iterator.
public void leggTilHandlekurv(String varenavn) {
Iterator<Varer> iterator = lagerplass.iterator();
while(iterator.hasNext()) {
Varer a = iterator.next();
if (a.getVarenavn().equals(varenavn)) {
iterator.remove();
hk.addVarer(a);
}
}
}
It is because you cannot modify a collection while iterating over it. Either use a for loop with indeces, or an Iterator over your collection and call the remove method.
Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
for (Iterator<Varer> iterator = lagerplass.iterator(); iterator.hasNext();) {
Varer a = iterator.next();
if (a.getVarenavn().equals(varenavn))
{
hk.addVarer(a);
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
Source:
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
I have a question regarding static method access. I have a class within i have 4 static method. as shown in code:
package com.itrucking.util;
public class ZKUtil implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
* #author Shekhar
* #param _class
* #param listbox
* To make Listbox sorting enabled
* #throws NoSuchMethodException
* #throws SecurityException
*/
public static void setSortingEnabled(Class<?> _class, Listbox listbox){
Map<Listheader, String> sortingPair = new HashMap<Listheader, String>();
sortingPair = getMapForSorting(_class, listbox);
if (!sortingPair.isEmpty()) {
for (Map.Entry<Listheader, String> entry : sortingPair.entrySet()) {
entry.getKey().setSortAscending(
new FieldComparator(entry.getValue(), true));
entry.getKey().setSortDescending(
new FieldComparator(entry.getValue(), false));
}
}
}
/**
* #author Shekhar
* #param _class
* #param listbox
* #return Map<Listheader, String>
*/
private static Map<Listheader, String> getMapForSorting(Class<?> _class,Listbox listbox) {
List<Listheader> headerList = getListHeaderList(listbox);
Map<Listheader, String> sortingPair = new HashMap<Listheader, String>();
System.out.println(_class);
Field[] fields = _class.getDeclaredFields();
for (Field f : fields) {
// System.out.println(f.getName()+":"+f.getType());
for (Listheader lh : headerList) {
if (f.getName().equals(getId(lh)))
sortingPair.put(lh, f.getName());
}
}
System.out.println(sortingPair);
return sortingPair;
}
private static String getId(Listheader listheader) {
String listheaderId = null;
if (listheader.getId().contains("_")) {
listheaderId = listheader.getId().split("_")[1];
// System.out.println("listheaderId->"+listheaderId);
}
return listheaderId;
}
/**
* #author Shekhar
* #param listbox
* #return List<Listheader>
*/
#SuppressWarnings("unchecked")
private static List<Listheader> getListHeaderList(Listbox listbox) {
List<Listheader> headerList = new ArrayList<Listheader>();
Listhead listhead = null;
List<Component> listboxComponentList = listbox.getChildren();
for (Component listboxComponent : listboxComponentList) {
if (listboxComponent instanceof Listhead) {
listhead = (Listhead) listboxComponent;
break;
}
}
List<Component> listOfComp = listhead.getChildren();
if (listhead != null) {
for (Component c : listOfComp) {
if (c instanceof Listheader)
headerList.add((Listheader) c);
}
}
return headerList;
}
}
and i am calling setSortingEnabled() method from onLoadShipperDetailsListCtrl() from code bellow :
package com.itrucking.webui.controller;
public class ShipperDetailsListCtrl{
/**
* #param e
* #return void
*/
public void onCreate$window_shipperDetailsList(Event e){
onLoadShipperDetailsListCtrl();
}
/**
* #return void
*/
public void onLoadShipperDetailsListCtrl(){
System.out.println("onLoadShipperDetailsListCtrl called.");
shipperList = shipperService.getShipperList();
doRenderListboxShipperDetailsList(shipperList);
ZKUtil.setSortingEnabled(ShipperMaster.class, listbox_shipperDetailsList);
}
}
so what i think if i am calling setSortingEnabled() method from other class so i kept is as public and other method's i kept as private but it's giving me error as :
java.lang.NoSuchMethodError: com/itrucking/util/ZKUtil.getMapForSorting(Ljava/lang/Class;Lorg/zkoss/zul/Listbox;)Ljava/util/Map;
Why there is error NoSuchMethodError for ZKUtil.getMapForSorting() call in setSortingEnabled()
I know we can call private method from public in the same class. So i am not able to understand what is the problem.
Thanks in advance.
A NoSuchMethodError (the runtime error saying a method can't be found, instead of a compiler error) usually means that the .class files you're using are of a different version than the files you compiled against. In this case, you probably made changes to ZKUtil.java, but the JVM is loading an outdated version of ZKUtil.class. Clean and rebuild all of your .class files.
In an answer to a question I asked, I was advised to solve a particular (irrelevant) problem by making a class (test_C) designed to test the main class (C) be a child class of C:
public class test_C extends C {
Is this a common pattern in Java development?
Are there any reasons NOT to use this pattern for all test classes (assume that we always have 1-1 mapping between test class and tested class)?
Are there any reasons NOT to use this pattern for all test classes (assume that we always have 1-1 mapping between test class and tested class)?
The class being tested can be final, preventing any class from subclassing it.
public final class C { ... }
If a testing subclass is feasible, it could alter the behavior of the class being tested -- unintentionally as well as intentionally.
1) Well, I do not know if it is a general pattern but i already used it and found some drawbacks.
2) the reasons to not do it are fairy simple. It is recommended to use private accessor and final class or method.
If you really apply the later, you will end up with producing many duplicate classes to test a class or a method. Also, How can you make sure somebody in your team will not end up using the dummy extended class in production?
My solution to this problem was to use reflection to access private constructors and methods. It is somehow a bit tricky but afterwards it is a repetition. I am using now my utility reflection class for all my tests.
Below is my reflection utility class:
import static org.junit.Assert.fail;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* The Class JunitReflectionUtils.
*/
public final class JunitReflectionUtils {
/**
* Instantiates a new junit reflection utils.
*/
private JunitReflectionUtils() {
}
/**
* Gets the method.
*
* #param givenClass_ the given class_
* #param methodName_ the method name
* #param failIfException_ if true, the method will fail
* #param parametersClass_ the parameters
* #return the method
*/
public static Method getMethod(Class<?> givenClass_, String methodName_, boolean failIfException_, Class<?> ... parametersClass_) {
Method _method = null;
try {
_method = givenClass_.getDeclaredMethod(methodName_, parametersClass_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("A method called \"" + methodName_ + "\" could not be retrieved: " + _exception.getMessage());
} else {
return null;
}
}
_method.setAccessible(true);
return _method;
}
/**
* Gets the field.
*
* #param givenClass_ the given class
* #param fieldName_ the field name
* #param failIfException_ if true then the method will fail if an exception is thrown
* #return the field
*/
public static Field getField(Class<?> givenClass_, String fieldName_, boolean failIfException_) {
Field _field = null;
try {
_field = givenClass_.getDeclaredField(fieldName_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("A field called \"" + fieldName_ + "\" could not be retrieved: " + _exception.getMessage());
} else {
return null;
}
}
_field.setAccessible(true);
return _field;
}
/**
* assign value to a field.
*
* #param field_ the given field
* #param parentObject_ the parent containing the field
* #param failIfException_ if true then the method will fail if an exception is thrown
* #param value_ the value to assign to the field
* #return the field
*/
public static boolean assignValueToField(Field field_, Object parentObject_, boolean failIfException_, Object value_) {
try {
field_.set(parentObject_, value_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An exception has occured while setting a value to a field: " + _exception.getMessage());
}
return false;
}
return true;
}
/**
* Gets the field value from a given object.
*
* #param object_ the object
* #param fieldName_ the field name
* #param failIfException_ if true, this method will fail if an exception is thrown
* #return the field value from object
*/
public static Object getFieldValueFromObject(Object object_, String fieldName_, boolean failIfException_) {
Field _givenField = getField(object_.getClass(), fieldName_, failIfException_);
Object _returnedValue = null;
if (_givenField == null) {
return null;
} else {
try {
_returnedValue = _givenField.get(object_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An exception has occured while retrieving a value from a field : " + _exception.getMessage());
} else {
return null;
}
}
}
return _returnedValue;
}
/**
* Gets the constructor.
*
* #param givenClass_ the given class
* #param failIfException_ if true, a fail statement will be issued when an exception is thrown
* #param parametersClasses_ the parameters classes_
* #return the constructor
*/
public static Constructor<?> getConstructor(Class<?> givenClass_, boolean failIfException_, Class<?> ... parametersClasses_) {
Constructor<?> _constructor = null;
try {
_constructor = givenClass_.getDeclaredConstructor(parametersClasses_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("The constructor from the class \"" + givenClass_.getName() + "\" could not be retrieved");
} else {
return null;
}
}
_constructor.setAccessible(true);
return _constructor;
}
/**
* Instantiante an object.
*
* #param givenClass_ the given class
* #param failIfException_ if true then a fail statement will be issued if an exception is thrown
* #param parametersClasses_ the parameters classes
* #param parameters_ the parameters
* #return the object
*/
public static Object instantianteAnObject(Class<?> givenClass_, boolean failIfException_, Class<?> [] parametersClasses_, Object... parameters_) {
Constructor<?> _constructor = getConstructor(givenClass_, failIfException_, parametersClasses_);
Object _returnedObject = null;
if (_constructor != null) {
try {
_returnedObject = _constructor.newInstance(parameters_);
} catch (Exception _exception) {
_exception.printStackTrace();
if (failIfException_) {
fail("An instance of " + givenClass_.getName() + " could not be created : " + _exception.getMessage());
} else {
return null;
}
}
}
return _returnedObject;
}
}