I have generic class type, T as follow:
class MyClass<T>
Also I know that T is interface with only one method inside but I don't know what interface, I can't write this:
class MyClass< T extends TheInterface >
So is there a way to invoke this method?
public void callMe(T me, Object...params){
// How can I invoke T interface method?
}
I been trying this:
public void callMe(T me, Object... params) {
// methods.length is 244, just as in my activity class
Method[] methods = me.getClass().getMethods();
try {
methods[0].invoke(me, params);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
return;
} catch (InvocationTargetException e) {
e.printStackTrace();
return;
}
}
But it's not working
Edit: I posted new question that explain why I need this for
Yes, you have to write:
class MyClass< T extends TheInterface >
With this information, the compiler know that T have an operation named callMe
I'm not sure, are you looking for the Strategy pattern?
If you can not change declaration inside MyClass then you can just typecast it.
public void callMe(T me, Object... params) {
Someinterface instance = (Someinterface) me;
list.callMe(me, params);
}
But still declaring it like below should be the best solution
class MyClass<T extends Someinterface >
Below is the simple demonstration of how to do it using reflection
class MyClass<T> {
public void callMe(T me, Object... params) throws SecurityException,
NoSuchMethodException {
// How can I invoke T interface method?
Method size = me.getClass().getMethod("size", null);
Method add = me.getClass().getMethod("add", Object.class);
try {
add.invoke(me, 10);
System.out.println(size.invoke(me, params));
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
} catch (IllegalAccessException e) {
e.printStackTrace();
return;
} catch (InvocationTargetException e) {
e.printStackTrace();
return;
}
}
}
MyClass<List> myclass = new MyClass<List>();
myclass.callMe(new ArrayList(), null);
Output :
1
Related
To sum up my project I'm trying to make an event processor that runs methods from a given list of methods. In order to invoke these methods I need to pass in the newInstance of the method. The method is correctly run, however, right after the whole program crashes with a "ConcurrentModificationException".
#EventHandler
private Listener<EventKeyInput> eventKeyInput = new Listener<>(event ->
{
for(Method m : event.getMethods())
{
try {
m.invoke(m.getDeclaringClass().newInstance(), event);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
One of the methods I wish to call
#EventAnnotation()
public void eventKeyInputeTest(EventKeyInput event)
{
System.out.println("EventKeyInput test!");
}
Please let me know if I need to provide anymore code. Thank you for any help!
Edit: Added the class where I change the method
Is there any other way to go about this?
for(Method m : listenable.getClass().getMethods())
{
if(m.isAnnotationPresent(EventAnnotation.class))
{
Parameter[] params = m.getParameters();
if(params.length != 1)
{
System.out.println("You need 1 event paramter!");
}
Class<?> eventType= params[0].getType();
try {
Object methods = eventType.getMethod("getMethods").invoke(eventType.newInstance(), null);
Method add = List.class.getDeclaredMethod("add", Object.class);
add.invoke(methods, m);
eventType.getMethod("setMethods", ArrayList.class).invoke(eventType.newInstance(), methods);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Suppose you have this code:
class Base {
void method() throws Exception {
try {
//Lots of code here
} catch (Exception e) {
//handle it (very little code here)
}
}
class Derived extends Base {
#Override
void method() throws Exception {
try {
//Lots of code here (same code as in base class)
} catch (Exception e) {
//handle it (very little code here; also same as base class)
} catch (Error e) {
e.printStackTrace();
System.exit(1);
}
}
So, as we can see, the methods are the same except the derived class has an extra catch clause. Is there a nice way to have a bit less duplicated code here?
May be it could be silly,but I want to clear my the technical understanding of this code:
import netscape.*;//ldap jar
public class A {
public void method() {
...
try {
//code is written here.
LDAPSearchResults lsr = ldi.search(LDAPConnectionInfo.MY_SEARCHBASE,LDAPConnectionInfo.MY_SCOPE,LDAPConnectionInfo.MY_FILTER,null,false);
while(lsr.hasMoreElements()){
LDAPEntry findEntry = (LDAPEntry)lsr.nextElement();
} catch(...) {
}
}
}
Now I call another class
public class B {
A a = new A();
//here I want to use attributeName
}
How could I access A class's member(in try block) in B class.
Any way to handle try block code for reuse in another class.
How could I handle all those exception in another class.
Any modification should I need...
Calling method of Object type.
public class C{
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public Object method(){
attributeName=lAttribute.getName();
}
}
How could print this Object type method into String(in a jsp page)... any inputs
You'll need a member in class A and a getter:
public class A {
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public void method(){
...
try {
//code is written here.
attributeName = lAttribute.getName();
}
catch() {
}
}
}
Then:
public class B {
A a = new A();
// somewhere
String str = a.getAttributeName();
}
There's no way to access a method's private variables like you did in the original example, as they only exist on the stack during the method call.
Edit: I noticed another question:
How could I handle all those exception in another class.
I assume you want to call your method somewhere else and catch the exceptions there. In that case you can use the throws keyword to communicate that your method will pass exceptions to the caller:
public class A {
public void method() throws IOException {
//code is written here.
String attributeName = lAttribute.getName();
}
public void anotherMethod() {
try {
method();
} catch(IOException ex) {
...
}
}
}
then if some other piece of code calls method it will be forced to either handle or further propagate the exception.
How could I handle all those exception in another class.
In your calling class you can catch Throwable (which will catch all exceptions and errors)
try {
....
}
catch (Throwable t) {
//do something with the throwable.
}
if you do not want to catch Errors (Ive only done this when messing around with ImageIO and had memory problems) in Java then catch Exception instead
Any way to handle try block code for reuse in another class
here you could create a method in another class and then call it within your try /catch block
public class XYX {
public void methodForTry() throws Exception {
//do something
}
}
try {
new XYZ().methodForTry();
}
catch (Exception e){
}
You may or may not want to create new XYZ here. It depends what state this object may or may not hold.
As to the last questions I think Tudor's answer covers this
Your question may be about extracting the code template
try { ... do stuff ... }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
Where you only want to change the ... do stuff ... part. In that case you'd need closures, which are coming with Java 8, and today you'd need something quite cumbersome, of this sort:
public static void tryCatch(RunnableExc r) {
try { r.run(); }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
}
where RunnableExc would be an
interface RunnableExc { void run() throws Exception; }
and you'd use it this way:
tryCatch(new RunnableExc() { public void run() throws Exception {
... do stuff ...
}});
why not return it?
public String method() {
String attributeName
try {
//code is written here.
attributeName = lAttribute.getName();
} catch(...) {
}
return attributeName;
}
public class B {
A a = new A();
String attributeName = a.method();
}
I need to code a method, something like :
MyClassObject convert(Class MyClass , String value)
The convert method's job is to convert the String into an object of MyClass, where MyClass can be anything (except a primitive) - Integer, Boolean, Character, Date... the possibilities are huge here - and that's the reason I gave up my stupid if-else block to handle all the cases individually.
I could see something related to this for C# (don't know if it works) , don't know if we have a Java equivalent for this or this
I understand not everything can be converted from a string, I am ready to handle exceptions for non-parseable items.
I don't know if this is possible or not. If not, please help me with a proper design pattern for my code.
Thanks !
Your best bet is probably the ServiceLoader mechanism. This allows you to define a pair of interfaces, e.g.:
interface StringConverterProvider{
StringConverter<T> getConverterFor(Class<T> clazz);
}
interface StringConverter<T>{
T convert(String s);
}
... and then locate all the implementations of these interfaces available at runtime, like so:
ServiceLoader<StringConverterProvider> converterProviderLoader
= ServiceLoader.load(StringConverterProvider.class);
T convert(String s, Class<T> t){
for(StringConverterProvider scProv : converterProviderLoader){
StringConverter<T> converter = scProv.getConverterFor(t);
if (converter != null)
return converter.convert(s);
}
return null;
}
You make your implementation of the interfaces available to ServiceLoader by listing them in a special file in the META-INF directory in your jar file; see the javadoc for details.
Using reflection and hoping that all the wrapper objects for primitives contains a constructor with a string argument for value, you may be able to achieve this like the following
// A sample test with main
public static void main(String[] args) {
Object obj = create(Integer.class, "54896");
Integer val = (Integer) obj;
System.out.println(val);
}
// Method to create the desired object with the given value
private static Object create(Class myClass, String value) {
Object obj = null;
try {
Constructor constructor = myClass.getConstructor(new Class[]{String.class});
obj=constructor.newInstance(value);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException 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();
}
return obj;
}
I've made an abstract Thread that processes some streams in its run() method. I'd like to be able to have the subclasses handle these exceptions rather than the abstract parent class, but I don't know the most elegant way to do that. Right now, I'm doing something like this:
import org.apache.logging.log4j; // (I use log4j for logging)
public interface Loggable {
Logger getLogger();
}
public abstract class ParentThread extends Thread implements Loggable {
private final static Logger logger =
Logger.getLogger(ParentThread.class); // Logger with no Appenders
#Override
public void run() {
try {
// Do some stuff that throws exceptions
doAbstractStuff();
} catch (SomeSortOfException ex) {
getLogger().error("Oh noes!", ex);
} catch (SomeOtherException ex) {
getLogger().error("The sky is falling!", ex);
}
}
public Logger getLogger() { return logger; }
protected abstract void doAbstractStuff();
}
public class ChildThread extends ParentThread {
#Override
public Logger getLogger() { /* return a logger that I actually use */ }
#Override
public void doAbstractStuff() { /* Implementation */ }
}
I guess I should mention that the ChildThread is actually an inner class of my main form, and that its logger belongs to that form.
Another approach I thought of was to have an
abstract void handleException(Exception ex);
in ParentThread, but then I'm not able to handle individual exceptions from the ChildThread.
Your first solution seems conceptually wrong to me: mixing application-specific error-handling with generic logging.
Your second idea (the callback) seems a better solution and offers the possibility of abstracting away the implementation-specific exceptions for custom events, for example:
public abstract class Parent {
public void run() {
InputStream in = null;
try {
in = new URL("bladiebla").openConnection().getInputStream();
String text = // ...read text from InputStream
if (text == null || text.length() == 0) {
handleMyEvent(new NoInputEvent());
return;
}
doWork(text);
} catch (MalformedURLException e) {
handleMyEvent(new MyEvent(e));
} catch (IOException e) {
handleMyEvent(new MyEvent(e));
}
finally {
if (in != null) {
try {
in.close();
}
catch(IOException e) {
handleMyEvent(e);
}
}
}
}
abstract void doWork(String text);
abstract void handleMyEvent(MyEvent myEvent);
}
public class MyEvent {
private Exception exception;
public MyEvent() {}
public MyEvent(Exception exception) {//set it}
}
public class NoInputEvent extends MyEvent {
}
Well there's no difference between
} catch (SomeSortOfException ex) {
getLogger().error("Oh noes!", ex);
} catch (SomeOtherException ex) {
getLogger().error("The sky is falling!", ex);
}
and
if (ex instanceof SomeSortOfException) {
getLogger().error("Oh noes!", ex);
} else if (ex instanceof SomeOtherException) {
getLogger().error("The sky is falling!", ex);
}
although the latter may require some casting.
Your abstract handleException(Exception ex) idea is sound, I'd go with that. I'd be inclined to not make it abstract, though, and define a sensible default implementation in ParentThread, and allow ChildThread to override it if required.
Why is your base class logging exceptions ? Why not use what the platform provide Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) and let it do whatever instead of mixing logging w/ your do-stuff component.