How to invoke Array-name from IPSUM.java class to updateArticleView method by passing its name simply?
eg. in highlighted row, i want to achieve this article.setText(Ipsum.LateralPull[0]); dynamically
updateArticleView method
IPSUM.java
A very simple way to do that is to use a HashMap<String, String[]> and you can put each array to the map with its current field name as its key:
map.put("LateralPull", new String[]{"LateralPaull"});
So you can simply call:
map.get(name);
But If you don't want to use HashMap for any reason you can use java reflection. Here is a sample code:
public class Main {
public static void main(String[] args) {
try {
Test test = new Test();
Field field = Test.class.getDeclaredField("list");
String[] list = (String[]) field.get(test);
System.out.println(list[0]);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String[]> map = new HashMap<>();
map.put("hasahn", new String[]{"df"});
}
private static class Test{
String[] list = new String[]{"Item 1"};
}
}
The output is: Item 1.
Related
Below is code for which i'm trying to write text case and added what i did but getting null pointer exp
public boolean doVersionLimitCheck(Long mneId) throws DMMException {
CALogUtil.getInstance().logMethodEntry("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
boolean status = false;
status = validateArchivedVersions(mneId);
CALogUtil.getInstance().logDebug("Version Roll over status::" + status);
CALogUtil.getInstance().logMethodExit("doVersionLimitCheck",
ConfigArchiveManagerImpl.class.getName());
return status;
}
for this i did like below.
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = new ConfigArchiveManagerImpl();
try {
Mockito.doReturn(true).when(Mockito.mock(ConfigArchiveManagerImpl.class)).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
impl.doVersionLimitCheck(mneId);
} catch (DMMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to spy on the SUT in order to test one method and mock the other:
#Test
public void testDoVersionLimitCheck() {
Long mneId=Long.valueOf("123");
ConfigArchiveManagerImpl impl = Mockito.spy(new ConfigArchiveManagerImpl());
try {
Mockito.doReturn(true).when(impl ).validateArchivedVersions(Mockito.anyLong());
} catch (DMMException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I'm having trouble mocking a static method in a third-party library. I keep receiving a null-pointer exception when running the test, but I'm not sure why that is.
Here is the class and the void method that invokes the static method I'm trying to mock "MRClientFactory.createConsumer(props)":
public class Dmaap {
Properties props = new Properties();
public Dmaap() {
}
public MRConsumerResponse createDmaapConsumer() {
System.out.println("at least made it here");
MRConsumerResponse mrConsumerResponse = null;
try {
MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
System.out.println("made it here.");
mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return mrConsumerResponse;
}
}
Below is the test that keeps returning a null-pointer exception. The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class));
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {
#Test
public void testCreateDmaapConsumer() {
try {
Properties props = new Properties();
PowerMockito.mockStatic(MRClientFactory.class);
PowerMockito.doNothing().when(MRClientFactory.class);
MRClientFactory.createConsumer(Mockito.any(Properties.class));
//MRClientFactory.createConsumer(props);
Dmaap serverMatchCtrl = new Dmaap();
Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);
serverMatchCtrlSpy.createDmaapConsumer();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic
Especially you are missing a
#PrepareForTest(Dmaap.class)
…to denote the class which does the static call.
I want to retrieve the results of a method in a single string each time the function is called. I have a method which returns different results every time. I want to put all the results as a single string.
Tried to use append() method of java but the results are getting replaced every time as the function is called each time. but i need to retrieve the previous results as well.
my code is as follows.
public void createPanel2()
{
panel2 = new JPanel();
panel2.setLayout( new FlowLayout() );
query = new JLabel("query");
textbox =new JTextField(10);
submit = new JButton("submit");
panel2.add(query);
panel2.add(textbox);
panel2.add(submit);
submit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
String str =textbox.getText();
String serverUrl = "http://localhost:8983/solr/collection1";
SolrServer solr = new HttpSolrServer(serverUrl);
try {
for (SolrDocument next : simpleSolrQuery(solr, str +
"")) {
prettyPrint(System.out, next);
}
} catch (SolrServerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
initFilterAndButton();
}
SolrDocumentList simpleSolrQuery(SolrServer solr,
String query) throws SolrServerException {
SolrQuery solrQuery = new SolrQuery(query);
//SolrQuery query = new SolrQuery(searchTerm);
//query.setStart((pageNum - 1) * numItemsPerPage);
//query.setRows(numItemsPerPage);
//solrQuery.setRows(Integer.MAX_VALUE);
QueryResponse resp = solr.query(solrQuery);
//System.out.println("resp"+resp);
final SolrDocumentList hits = resp.getResults();
/*for (SolrDocument d : hits) {
for (Iterator<Map.Entry<String, Object>> i = d.iterator(); i
.hasNext();) {
Map.Entry<String, Object> e2 = i.next();
System.out.println(e2.getKey() + "\t" + e2.getValue());
}
System.out.println("------------------------");
}*/
System.out.println("hits"+resp.getElapsedTime());
System.out.println("size"+hits.size());
System.out.println("num found"+hits.getNumFound());
//String str ="hello";
//createPanel1(hits);
return hits;
}
void prettyPrint(PrintStream out, SolrDocument doc) {
List<String> sortedFieldNames =
new ArrayList<String>(doc.getFieldNames());
Collections.sort(sortedFieldNames);
out.println();
// StringBuilder contentstring=new StringBuilder();
// ArrayList<String> contents=new ArrayList<>();
for (String field : sortedFieldNames) {
if(field.equals("content")){
textarea.append(String.format("%s: %s",
field,doc.getFieldValue(field)+"\n"));
out.println(String.format("\t%s: %s",
field, doc.getFieldValue(field)));
contentsmethod(doc.getFieldValue(field).toString());
// contents.add(doc.getFieldValue(field).toString());
// System.out.println("conetnts"+contentstring);
}
}
// String test=contentstring.toString();
out.println();
}
public void contentsmethod(String fieldsvalues) {
// TODO Auto-generated method stub
StringBuilder contentstring=new StringBuilder();
contentstring.append(fieldsvalues);
try {
Desktop.getDesktop().browse(new URL(serverQuery+URLEncoder.encode(contentstring.toString())).toURI());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
The code above is calling the prettyPrint method every time and the results of that method should be retrieved to a single string which should hold the previous called results as well.
here i want to retrieve the results of contentstring.append(fieldsvalues);
But contentstring is returning only the current results and not appending the previous results.
this is obvious because the method is called everytime. Is there any work around to retrieve the previous results along with the current ones as well.
You need to move this StringBuilder contentstring=new StringBuilder(); outside of your method. Every time your method call is made, you create a new String. This is why you only get the current value.
You can make a List outside of your method and add the resulting String in that list. Otherwhise, you can create the string outside and append the results to it without instantiating a new one at every method call.
You have to do something like this:
StringBuilder contentstring = new StringBuilder();
public void contentsmethod(String fieldsvalues) {
// TODO Auto-generated method stub
contentstring.append(fieldsvalues);
try {
Desktop.getDesktop().browse(new URL(serverQuery+URLEncoder.encode(contentstring.toString())).toURI());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have an Activity Class Anmeldung, a normal java class thread_haupt.class and a Activity funktionen_haupt.class.
on Start of Anmeldung.class starts a function(funktionstarter) of threads_haupt.class
This calls a function from functionen_haupt.class via invoke.
The idea is to have a function that can start other functions also from other classes
the problem is java.lang.InstantiationException: can't instantiate class … no empty constructor in my thread_haupt.class when I try to newInstance() (see below in thread_haupt.class)
java.lang.InstantiationException: can't instantiate class … no empty constructor
Anmeldung.Class
public class anmeldung extends Activity implements OnClickListener{
#Override
protected void onStart() { // start ist dann aufgerufen wenn alles gebaut ist
// TODO Auto-generated method stub
meine_funktionen.buttons_vorbereiten(this);
/**
* hier wirde zuerst der spinner befüllt
*/
thread_haupt meinThread = new thread_haupt();
//HOMEPAGE,naj.nuz.wz.wa.dc.kommunikation.allgemein kommunikation,naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein helfer, Activity meineAct};
meinThread.meine_parameter= new Object[] {HOMEPAGE,kommunikation,helfer,meineAct};
meinThread.meine_funktion="staedte_abfragen";
meinThread.mein_context=this.getApplicationContext();
meinThread.meine_activity=this;
meinThread.thread_starten("staedte_abfragen"); // HERE !!!
threads.class
public class thread_haupt {
public Object[] meine_parameter;
public String meine_funktion;
public Object mein_context;
public Activity meine_activity;
public allgemein mein_helfer = new allgemein();
public funktionen_haupt meine_funktionen = new funktionen_haupt((Context) mein_context, meine_activity);
/**
* hier sollen die threads gestartet werden
* #param threadName
*/
public void thread_starten(String threadName){
switch (threadName) {
case "staedte_abfragen":
//Thread thread = new Thread(new Runnable(){
//hier hab ich das gefunden http://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi
//public void run() {
//meine_funktionen.staedte_abfragen(HOMEPAGE,kommunikation,helfer, meineAct);
try {
meine_funktionen.funktionstarter("naj.nuz.wz.wa.dc.drinkcoffee.funktionen_haupt", meine_funktion, meine_parameter, mein_context);
// hier aufgehört dies startet nicht
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//}
//});
//thread.start();
break;
default:
break;
}
}
}
funktionen_haupt.class
public class funktionen_haupt extends Activity {
// CONTEXT empfangen von den die die klasse aufrufen
Context mContext;
Activity mActivity;
allgemein kommunikation = new allgemein();
naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein helfer = new naj.nuz.wz.wa.dc.drinkcoffee.helfer.allgemein();
public funktionen_haupt(Context mContext,Activity mActivity){
this.mContext = mContext;
this.mActivity=mActivity;
}
public void funktionstarter(String package_name,String funktion_name,Object[] arguments, Object meincontext) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, java.lang.InstantiationException {
//no paramater
Method[] methoden;
Class cls = null;
Object obj = null;
try {
cls = Class.forName(package_name);
obj = cls.newInstance(); // !!! HERE IS MY PROBLEM !!!!
//Constructor<funktionen> obj = cls.getConstructor(cls);
//funktionen dieklasse = obj.newInstance(null);
//Object obj = FactoryRegistry.getFactory(cls).newInstance();
methoden = cls.getDeclaredMethods();
for (int i =0;i<=methoden.length-1;i++){
if (methoden[i].getName().equals(funktion_name)){
Method method2 =cls.getDeclaredMethod(funktion_name, methoden[i].getParameterTypes());
if (meincontext==null){
method2.invoke(obj, arguments);
}
else{
method2.invoke(meincontext, arguments);
}
break;
}
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
methoden = cls.getDeclaredMethods();
for (int i =0;i<=methoden.length-1;i++){
if (methoden[i].getName().equals(funktion_name)){
Method method2 =cls.getDeclaredMethod(funktion_name, methoden[i].getParameterTypes());
method2.invoke(this, arguments);
break;
}
}
}
}
I get an exeption by
cls = Class.forName(package_name);
obj = cls.newInstance(); // java.lang.InstantiationException: can't instantiate class … no empty constructor
and I don´t know why.
Can somone tell me whats wrong, why it´s not working and what I doing wrong ?
Thanks in advance.
Because you declared a constructor with different parameters, the default (empty) constructor is gone. The default constructor is only available when you have not defined another constructor.
You can create an empty constructor like this:
public funktionen_haupt(){
}
public funktionen_haupt(Context mContext,Activity mActivity){
this.mContext = mContext;
this.mActivity=mActivity;
}
If you want to create the object with the parameters then you should not use the newInstance() method but just call the constuctor.
I'm trying to load the radio version of the Android device using reflection. I need to do this because my SDK supports back to API 7, but Build.RADIO was added in API 8, and Build.getRadioVersion() was added in API 14.
// This line executes fine, but is deprecated in API 14
String radioVersion = Build.RADIO;
// This line executes fine, but is deprecated in API 14
String radioVersion = (String) Build.class.getField("RADIO").get(null);
// This line executes fine.
String radioVersion = Build.getRadioVersion();
// This line throws a MethodNotFoundException.
Method method = Build.class.getMethod("getRadioVersion", String.class);
// The rest of the attempt to call getRadioVersion().
String radioVersion = method.invoke(null).toString();
I'm probably doing something wrong here. Any ideas?
Try this:
try {
Method getRadioVersion = Build.class.getMethod("getRadioVersion");
if (getRadioVersion != null) {
try {
String version = (String) getRadioVersion.invoke(Build.class);
// Add your implementation here
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.wtf(TAG, "getMethod returned null");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
What Build.getRadioVersion() actually does is return the value of gsm.version.baseband system property. Check Build and TelephonyProperties sources:
static final String PROPERTY_BASEBAND_VERSION = "gsm.version.baseband";
public static String getRadioVersion() {
return SystemProperties.get(TelephonyProperties.PROPERTY_BASEBAND_VERSION, null);
}
According to AndroidXref this property is available even in API 4. Thus you may get it on any version of Android through SystemProperties using the reflection:
public static String getRadioVersion() {
return getSystemProperty("gsm.version.baseband");
}
// reflection helper methods
static String getSystemProperty(String propName) {
Class<?> clsSystemProperties = tryClassForName("android.os.SystemProperties");
Method mtdGet = tryGetMethod(clsSystemProperties, "get", String.class);
return tryInvoke(mtdGet, null, propName);
}
static Class<?> tryClassForName(String className) {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
}
static Method tryGetMethod(Class<?> cls, String name, Class<?>... parameterTypes) {
try {
return cls.getDeclaredMethod(name, parameterTypes);
} catch (Exception e) {
return null;
}
}
static <T> T tryInvoke(Method m, Object object, Object... args) {
try {
return (T) m.invoke(object, args);
} catch (InvocationTargetException e) {
throw new RuntimeException(e.getTargetException());
} catch (Exception e) {
return null;
}
}