Create an instance of a class and initialize all its fields - java

I want to create an instance of a class, but I also need to initialize also all its fields recursively.
The code you see related do the objectFactory is because some of this classes could be JAXB classes, so for every package there is an ObjectFactory with methods like createJaxbObject(....).
EDITED:
My final solutions is this one:
public Object getInstance(Class<?> instanceClass, Boolean simple,
String jaxbName) {
Object instance = null;
try {
if (instanceClass.isPrimitive())
return primitiveValues.get(instanceClass.getName());
if (List.class.isAssignableFrom(instanceClass))
return new ArrayList();
else if (instanceClass.isEnum())
return instanceClass.getEnumConstants()[0];
else if (instanceClass.isArray())
return java.lang.reflect.Array.newInstance(instanceClass, 1);
else if (BigInteger.class.isAssignableFrom(instanceClass))
return new BigInteger("0");
else if (instanceClass.equals(String.class))
return "";
else if (instanceClass.equals(Boolean.class))
return false;
else if (instanceClass.equals(EntityObjectStringType.class))
return new EntityObjectStringType();
else if (JAXBElement.class.isAssignableFrom(instanceClass)) {
try {
Method m = null;
Class<?> objFactoryClass = null;
Iterator<String> it = EditorServlet.objectFactories
.iterator();
Object of = null;
while (it.hasNext()) {
objFactoryClass = Class.forName(it.next());
of = objFactoryClass.getConstructor().newInstance();
m = getMethodFromObjectFactory(objFactoryClass,
jaxbName);
if (m != null)
if (m.getParameterTypes().length > 0)
break;
}
Object jaxbElement = getInstance(m.getParameterTypes()[0],
m.getParameterTypes()[0].getSimpleName());
return m.invoke(of, jaxbElement);
} catch (NoSuchMethodException e) {
logger.error("JAXB NoSuchMethodException");
}
} else
try {
logger.info("Costruttori per " + instanceClass.getName()
+ " " + instanceClass.getConstructors().length);
instance = instanceClass.getConstructor().newInstance();
} catch (NoSuchMethodException noSuchMethodException) {
logger.error("getConstructors NoSuchMethodException");
}
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException " + instanceClass.getName());
} catch (SecurityException e) {
logger.error("SecurityException " + instanceClass.getName());
} catch (InstantiationException e) {
logger.error("InstantiationException " + instanceClass.getName()
+ " " + instanceClass.isPrimitive());
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException " + instanceClass.getName());
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException " + instanceClass.getName());
} catch (ClassNotFoundException e) {
logger.error("ClassNotFoundException " + instanceClass.getName());
}
if (!simple) {
for (Field field : instanceClass.getDeclaredFields()) {
try {
Object fieldInstance = getInstance(field.getType(),
field.getName());
field.setAccessible(true);
field.set(instance, fieldInstance);
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException "
+ instanceClass.getName());
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException "
+ instanceClass.getName());
}
}
}
return instance;
}

If I could hazard a guess, you're calling your method recursively in your NoSuchMethodException catch.
Object of = getInstance(objFactoryClass);
If your recursive call keeps on not finding the method on:
Method m = getMethodFromObjectFactory(objFactoryClass, c);
... the method will call itself again, which should end with a StackOverflowError at some point.

Your recursion has no break point
Try to stop recursion where the class is primary type:
if (List.class.isAssignableFrom(c))
instance = new ArrayList();
else if (c.isEnum())
return c.getEnumConstants()[0]; //avoid stackoverflow error
else if(c.isPrimitive()) {
instance = c.getConstructor().newInstance();
// use must stop here
return instance;
} else{
instance = c.getConstructor().newInstance();
}
The isPrimitive will judge whether the class is primary type(int ,Integer,shor,Short,String...)

Related

Return a string from void

hello I have this programming assignment where I have to use the functions they gave us, as they give it to us to use, the problem i am encountering is the fact this has to be void and I am not allowed to use System.out.println(); either so my question is how to i return the exception without changing the method header or it using System.out.println();?
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
System.out.println("ITEM " + itemID + " DOES NOT EXIST!");
}
}
In your catch block do this:
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("ITEM " + itemID + " DOES NOT EXIST!");
}
You don't need to add a throw declaration to your method, since IndexOutOfBoundsException is a RuntimeException.
Where ever you call the function you can add a catch block to read the error message like this:
catch (IndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
Well, if the method is used incorrectly (without validation of the index), maybe it should throw an exception?
You can remove the try-catch block completely. IndexOutOfBoundsException is a runtime exception, so it does not require the throws IndexOutOfBoundsException syntax.
However, if you want the exception to be less cryptic, you can wrap it with your own RuntimeException:
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeException("Invalid item ID: " + itemID, e);
}
}
You can change your method signature and throw an exception
public void deleteItem(String itemID) throws Exception{
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}catch (IndexOutOfBoundsException e) {
Exception ex = new Exception("ITEM " + itemID + " DOES NOT EXIST!");
throw ex;
}
}
Once done you can get your error message like this
try{
xxx.deleteItem("your itemID");
}catch(Exception e){
// You will read your "ITEM " + itemID + " DOES NOT EXIST!" here
String yourErrorMessage = e.getMessage();
}
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException( "ITEM " + itemID + " DOES NOT EXIST!");
}
}
public void deleteItem(String itemID)throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
You cant return exceptions . Exceptions are thrown from the methods , you can use keyword throw for that.try above methods to throw exceptions from methods
Remove try..catch block and modify your function as
public void deleteItem(String itemID) throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
Add try catch where you call this method and use System.out.println("ITEM " + itemID + " DOES NOT EXIST!"); there.
Ya even if you do not add throws to this method but put call of deleteItem in try catch block will work.

How to solve this chicken and egg issue?

I saw similar questions here on SO, but, I am asking this question based on this.
I have implemented the suggestion given by the accepted answer but, still I see two instances being created. The goal is that I want an instance to be created only on a particular method call. I can't use static method in an interface with Java 6.
The code I have tried
private static final Map<String, IRule> instancesMap = new Hashtable<String, IRule>();
#SuppressWarnings("unchecked")
public static <T extends IRule> T getRuleInstance(String clazz) {
try {
if (isInstanceCreated(clazz)) {
T type = (T) instancesMap.get(clazz);
if (logger.isDebugEnabled()) {
logger.debug("Found a cashed instance of " + clazz + ". Returning " + type);
}
return type;
} else {
Class<?> ruleObject = Class.forName(clazz);
Constructor<?> clazzConstructor = ruleObject.getDeclaredConstructor();
/**
* Hack encapsulation
*/
clazzConstructor.setAccessible(true);
IRule iRuleInstance = (IRule) clazzConstructor.newInstance();
if (logger.isDebugEnabled()) {
logger.debug("The instance of class " + clazz + " " + iRuleInstance + " has been created.");
}
instancesMap.put(clazz, iRuleInstance);
return (T) iRuleInstance.getInstance();
}
} catch (ClassNotFoundException e) {
logger.error("ClassNotFoundException", e);
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException", e);
} catch (SecurityException e) {
logger.error("SecurityException", e);
} catch (NoSuchMethodException e) {
logger.error("NoSuchMethodException", e);
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException", e);
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException", e);
} catch (InstantiationException e) {
logger.error("InstantiationException", e);
}
return null;
}
private static boolean isInstanceCreated(String clazz) {
return instancesMap.containsKey(clazz);
}
At the moment if there's a cache hit, you return the contents of the cache (instancesMap.get(clazz)). But if no hit, you cache one thing (instancesMap.put(clazz, iRuleInstance)) and return another (iRuleInstance.getInstance()). That doesn't make sense.
Don't call getInstance after adding to map, just return it:
instancesMap.put(clazz, iRuleInstance);
return (T) iRuleInstance;
Or, do call getInstance, but cache it:
(T) instance = iRuleInstance.getInstance();
instancesMap.put(clazz, instance);
return (T) instance;
Either way you must return what you cache so that it matches your logic for a cache hit.
Is there a particular reason why you need to have the concrete implementation of IRule?-- what methods are you going to be using from the implementation? Can't they be generalised into the interface itself? If this is the case, you could just have a map of Map<Class<? extends IRule>, IRule> to manage your instances.

Can't catch Java (Android) Exception with try-catch

I'm a Java (Android) beginner (coming from Python) and I'm trying to catch an exception using Try-Catch as follows:
try {
u.save();
} catch (Exception e) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}
To my surprise I don't see my Log message but I still get the following error:
09-25 10:53:32.147: E/SQLiteDatabase(7991):
android.database.sqlite.SQLiteConstraintException: error code 19:
constraint failed
Why doesn't it catch the Exception? Am I doing something wrong here? All tips are welcome!
The save() method looks as follows:
public final void save() {
final SQLiteDatabase db = Cache.openDatabase();
final ContentValues values = new ContentValues();
for (Field field : mTableInfo.getFields()) {
final String fieldName = mTableInfo.getColumnName(field);
Class<?> fieldType = field.getType();
field.setAccessible(true);
try {
Object value = field.get(this);
if (value != null) {
final TypeSerializer typeSerializer = Cache.getParserForType(fieldType);
if (typeSerializer != null) {
// serialize data
value = typeSerializer.serialize(value);
// set new object type
if (value != null) {
fieldType = value.getClass();
// check that the serializer returned what it promised
if (!fieldType.equals(typeSerializer.getSerializedType())) {
Log.w(String.format("TypeSerializer returned wrong type: expected a %s but got a %s",
typeSerializer.getSerializedType(), fieldType));
}
}
}
}
// TODO: Find a smarter way to do this? This if block is necessary because we
// can't know the type until runtime.
if (value == null) {
values.putNull(fieldName);
}
else if (fieldType.equals(Byte.class) || fieldType.equals(byte.class)) {
values.put(fieldName, (Byte) value);
}
else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) {
values.put(fieldName, (Short) value);
}
else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) {
values.put(fieldName, (Integer) value);
}
else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) {
values.put(fieldName, (Long) value);
}
else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) {
values.put(fieldName, (Float) value);
}
else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) {
values.put(fieldName, (Double) value);
}
else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) {
values.put(fieldName, (Boolean) value);
}
else if (fieldType.equals(Character.class) || fieldType.equals(char.class)) {
values.put(fieldName, value.toString());
}
else if (fieldType.equals(String.class)) {
values.put(fieldName, value.toString());
}
else if (fieldType.equals(Byte[].class) || fieldType.equals(byte[].class)) {
values.put(fieldName, (byte[]) value);
}
else if (ReflectionUtils.isModel(fieldType)) {
values.put(fieldName, ((Model) value).getId());
}
else if (ReflectionUtils.isSubclassOf(fieldType, Enum.class)) {
values.put(fieldName, ((Enum<?>) value).name());
}
}
catch (IllegalArgumentException e) {
Log.e(e.getClass().getName(), e);
}
catch (IllegalAccessException e) {
Log.e(e.getClass().getName(), e);
}
}
if (mId == null) {
mId = db.insert(mTableInfo.getTableName(), null, values);
}
else {
db.update(mTableInfo.getTableName(), values, "Id=" + mId, null);
}
Cache.getContext().getContentResolver()
.notifyChange(ContentProvider.createUri(mTableInfo.getType(), mId), null);
}
There are two classes to catch the problems.
Error
Exception
Both are sub-class of Throwable class. When there is situation we do not know, that particular code block will throw Exception or Error? You can use Throwable. Throwable will catch both Errors & Exceptions.
Do this way
try {
u.save();
} catch (Throwable e) {
e.printStackTrace();
}
Constraint failed usually indicates that you did something like pass a null value into a column that you declare as not null when you create your table.
do this way
try {
// do some thing which you want in try block
} catch (JSONException e) {
e.printStackTrace();
Log.e("Catch block", Log.getStackTraceString(e));
}
Try
try {
u.save();
} catch (SQLException sqle) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}catch (Exception e) {
Log.wtf("DO THIS", " WHEN SAVE() FAILS");
}
Log is expecting certain variable-names like verbose(v), debug(d) or info(i).
Your "wtf" doesnt belong there. Check this answer for more info -->
https://stackoverflow.com/a/10006054/2074990
or this:
http://developer.android.com/tools/debugging/debugging-log.html

Determine if a Method is a `RemotableViewMethod`

I am building a Widget which contains a ProgressBar. If the Widget is computing I set the visibility of that ProgressBar to VISIBLE, and to INVISIBILE if all computings stopped. There should be no Problem, because the setVisibility is documented as RemotableViewMethod. However some guys at HTC seem to forget it, (i.e on the Wildfire S), so a call to RemoteViews.setVisibility will result in a crash. For this reason I try to implement a check, if setVisibility is really callable. I have writen this Method for it:
private boolean canShowProgress(){
LogCat.d(TAG, "canShowProgress");
Class<ProgressBar> barclz = ProgressBar.class;
try {
Method method = barclz.getMethod("setVisibility", new Class[]{int.class});
Annotation[] anot = method.getDeclaredAnnotations();
return anot.length > 0;
} catch (SecurityException e) {
LogCat.stackTrace(TAG, e);
} catch (NoSuchMethodException e) {
LogCat.stackTrace(TAG, e);
}
return false;
}
This will work, but is REALLY ugly as it will return `True´ if ANY Annotiation is present. I looked, how RemoteView itself is doing the lookup and found this:
if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
throw new ActionException("view: " + klass.getName()
+ " can't use method with RemoteViews: "
+ this.methodName + "(" + param.getName() + ")");
}
But i could't do the same, because the Class RemotableViewMethod is not accsesible through the sdk. How to know if it is accesible or not?
By Writing my question I had the Idea to lookup for the class by its Name, and it worked.
So I updated my Method to the following:
private boolean canShowProgress(){
LogCat.d(TAG, "canShowProgress");
Class<ProgressBar> barclz = ProgressBar.class;
try {
Method method = barclz.getMethod("setVisibility", new Class[]{int.class});
Class c = null;
try {
c = Class.forName("android.view.RemotableViewMethod");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (this.showProgress= (c != null && method.isAnnotationPresent(c)));
} catch (SecurityException e) {
LogCat.stackTrace(TAG, e);
} catch (NoSuchMethodException e) {
LogCat.stackTrace(TAG, e);
}
return false;
}
which works flawlessly

Extracting and setting enum Values via reflection

I am trying to set a number of Enums to default value I am using the following method:
private void checkEnum(Field field, String setMethod) {
// TODO Auto-generated method stub
try {
String className = Character.toUpperCase(field.getName().charAt(0)) +
field.getName().substring(1);
Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
Object[] enumArray = cls.getEnumConstants();
//set to the last Enum which is unknown
invoke(setMethod, enumArray[enumArray.length - 1] );
} catch(Exception e) {
System.out.println(e.toString());
}
}
The problem is actually setting the Enum. I have extracted the enum type but to then call the MethodInvoker. Passing in the Enum object is proving a problem. All the enums have the following as the last element of the enum array.
EnumName.UNKNOWN
However this is not being set via the invoke method which looks like:
private Object invoke(String methodName, Object newValue) {
Object value = null;
try {
methodInvoker.setTargetMethod(methodName);
if (newValue != null) {
methodInvoker.setArguments(new Object[]{newValue});
} else {
methodInvoker.setArguments(new Object[]{});
}
methodInvoker.prepare();
value = methodInvoker.invoke();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (java.lang.reflect.InvocationTargetException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
return value;
}
So I'm lost as to why the
invoke(setMethod, enumArray[enumArray.length -1] );
Is not setting my Enum
I attempted to get your code running. The methodInvoker.prepare() call was throwing:
java.lang.IllegalArgumentException: Either 'targetClass' or 'targetObject' is required
So I added in the class missing parameter and the code works, if I understand your use case.
You appear to be setting a static field whose name must be the name of an Enum class under com.citigroup.get.zcc.intf with the first character in the field name downcased.
Here is my modified code:
public void checkEnum(Field field, String setMethod, Class clazz) {
try {
String className = Character.toUpperCase(field.getName().charAt(0)) +
field.getName().substring(1);
Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
Object[] enumArray = cls.getEnumConstants();
//set to the last Enum which is unknown
invoke(setMethod, enumArray[enumArray.length - 1], clazz);
} catch (Exception e) {
System.out.println(e.toString());
}
}
private Object invoke(String methodName, Object newValue, Class clazz) {
Object value = null;
try {
MethodInvoker methodInvoker = new MethodInvoker(); // this was missing
methodInvoker.setTargetMethod(methodName);
methodInvoker.setTargetClass(clazz); // This was missing
if (newValue != null) {
methodInvoker.setArguments(new Object[]{newValue});
} else {
methodInvoker.setArguments(new Object[]{});
}
methodInvoker.prepare();
value = methodInvoker.invoke();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (java.lang.reflect.InvocationTargetException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
}
return value;
}
}
My test code resembled (Show is an enum class of mine, MethodNameHelper has been previously posted to StackExchange):
public class StackExchangeTestCase {
protected static final Logger log = Logger.getLogger(StackExchangeTestCase.class);
public static Show show;
public static void setShow(Show newShow) {
show = newShow;
}
#Test
public void testJunk() throws Exception {
Method me = (new Util.MethodNameHelper(){}).getMethod();
Class<?> aClass = me.getDeclaringClass();
Field att1 = aClass.getField("show");
show = null;
methodNameHelper.checkEnum(att1, "setShow", aClass);
System.out.println(show); // worked
}
}

Categories