jeudi 8 décembre 2022

Java/Android reflection: type casting of Intent's Extra

In a system with Android (minimum Sdk 26) there is a package with a class of this kind: `

public class Example implements Serializable {
`    `private String[] field1;
`    `private ArrayList<Integer> field2;

`    `public method1(String[] field1, ArrayList<Integer> field2) {
`        `this.field1 = field1;
`        `this.field2 = field2;
`    `}

`    `private String method2 {
`        `// Some method that returns a String
`    `}
}

`

My package receives an object (an instance of that class) through an intent 'i', sent in this way:

Intent i = new Intent();  
i.putExtra("key", obj);  
setResult(Activity.RESULT_OK, i);  
finish();  

I do not have the full java file of class Example. However, my package (different from the one that sends the intent. It is in a separate apk) contains a Class object 'cl' of class Example (obtained through reflection) and a method object 'met' (method2, obtained through reflection as well). I need to call such method on the received object and print the resulting String on the Logs. How can this be done?

I tried the following:

met.setAccessible(true);  
String s = (String) met.invoke(cl.cast(i.getSerializableExtra("key")), null);  
if (s != null){  
`    `Log.d("TAG", s);  
} else{  
`    `Log.e("TAG", "null");  
}  

But nothing is printed on the log. I also tried this:

met.setAccessible(true);  
String s = (String) met.invoke(cl.cast(i.getSerializableExtra("key")), (Object) null);  
if (s != null){  
`    `Log.d("TAG", s);  
} else{  
`    `Log.e("TAG", "null");  
}  

But the same happened. Moreover, I tried to invoke the method through:

cl.cast(i.getExtras())

Instead of the previous case, but I obtained a Class Cast Exception (which I think is because intent.getExtras() returns a Bundle)





Aucun commentaire:

Enregistrer un commentaire