Win a copy of Beginning Java 17 Fundamentals: Object-Oriented Programming in Java 17 this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Dynamic casting using getMethod

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I need the help. How I do dynamic casting using reflection ? I must to pass only the class name.
My code is it:
...
Class classe = null;
// father of TransactionProcessor
Module md = null;
Method method = null;
try{
classe = Class.forName(classname);
// getInstnce is the SingleTon class and return TransactionProcessor type
method = classe.getMethod("getInstance", null);
// md = ( TransactionProcessor ) method.invoke(null,null); I CANT DO IT because it is a code generic.
md = ( ??? ) method.invoke(null,null);
md.run();
}catch(){};
I know that I can get the type of return using:
method.getReturnType().getName();
,but I can do the dynamica casting ?
Thanks
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you want to call a method on the object (the run method in the example), you already need to know its type at compile time anyway (for example Runnable), so you can cast to that. No "dynamic casting" necessary.
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic