Passing a class to a method?
This doesn't work:
public Decorator findDecorator(String className) {
if (this instanceof className)
return this;
else
return null;
}My friend told me that in C# he just does this:
findDecorator(Type className)So how do I do it in Java?
Edited by: hidarikani on Apr 2, 2009 11:35 AM
You can use isAssignableFrom, but I've never needed to do this. Makes me wonder just what you are doing.
Demo:
public class Test {
public static boolean hasType(Object x, Class<?> cls) {
if (x == null) {
return false;
} else {
return cls.isAssignableFrom(x.getClass());
static void test(Object x, Class<?> cls) {
System.out.format("new %s() hasType %s = %b%n",
x.getClass().getName(), cls.getName(), hasType(x, cls));
public static void main(String[] args) {
//trues
test(new A(), A.class);
test(new AA(), AA.class);
test(new AAA(), AAA.class);
test(new AA(), A.class);
test(new AAA(), AA.class);
test(new AAA(), A.class);
System.out.println();
//falses
test(new B(), A.class);
test(new A(), AA.class);
test(new A(), AAA.class);
test(new AA(), AAA.class);
class A {}
class AA extends A {}
class AAA extends AA {}
class B {}
Similar Messages
-
Passing Inner class name as parameter
Hi,
How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
Hope somebody can help me.
Thanks in advance.
PremNo, because an inner class can never have a constructor that doesn't take any arguments.
Without going through reflection, you always need an instance of the outer class to instantiate the inner class. Internally this instance is passed as a parameter to the inner class's constructor. So to create an instance of an inner class through reflection you need to get the appropriate constructor and call its newInstance method. Here's a complete example:import java.lang.reflect.Constructor;
class Outer {
class Inner {
public static void main(String[] args) throws Exception{
Class c = Class.forName("Outer$Inner");
Constructor cnstrctr = c.getDeclaredConstructor(new Class[] {Outer.class});
Outer o = new Outer();
Inner i = (Inner) cnstrctr.newInstance(new Object[]{o});
System.out.println(i);
} -
How to call a java method so I can pass a file into the method
I want to pass a file into a java method method from the main method. Can anyone give me some help as to how I pass the file into the method - do I pass the file name ? are there any special points I need to put in the methods signature etc ?
FileReader file = new FileReader("Scores");
BufferedReader infile = new BufferedReader(file);
Where am I supposed to put the above text - in the main method or the one I want to pass the file into to?
ThanksIt's a matter of personal preference really. I would encapsulate all of the file-parsing logic in a separate class that implements an interface so that if in the future you want to start taking the integers from another source, e.g. a db, you wouldn't need to drastically alter your main application code. Probably something like this, (with an assumption that the numbers are delimited by a comma and a realisation that my file-handling routine sucks):
public class MyApp{
public static void main(String[] args){
IntegerGather g = new FileIntegerGatherer();
Integer[] result = g.getIntegers(args[0]);
public interface IntegerGatherer{
public Integer[] getIntegers(String location);
import java.io.*;
public class FileIntegerGatherer implements IntegerGatherer{
public Integer[] getIntegers(String location){
FileInputStream fs=null;
try{
File f = new File(location);
fs = new FileInputStream(f);
byte[] in = new byte[1024];
StringBuffer sb = new StringBuffer();
while((fs.read(in))!=-1){
sb.append(new String(in));
StringTokenizer st = new StringTokenizer(sb.toString(),",");
Integer[] result = new Integer[st.countTokens()];
int count = 0;
while(st.hasMoreTokens()){
result[count]=Integer.valueOf(st.nextToken());
count++;
catch(IOException e){
//something sensible here
finally{
if(fs!=null){
try{
fs.close();
catch(IOException f){
return result;
Once compiled you could invoke it as java MyApp c:\myInts.txt
Sorry if there are typos in there, I don't have an ide open ;-> -
Passing select-options value in method
How to pass select-options value in method ?
Example:
Select-options: carrid for spfli-carrid.
class cl_myclass implementation.
select carrid connid from
spfli where carrid in carrid.
endclass.
ThanksHello Anee
The coding of this functionality is quite simple:
REPORT zmy_report.
DATA: go_myclass TYPE REF TO zcl_myclass,
gd_repid TYPE syst-repid.
PARAMETERS:
p_bukrs ...
SELECT-OPTIONS:
o_kunnr ...
START-OF-SELECTION.
gd_repid = syst-repid.
CREATE OBJECT go_myclass
EXPORTING
id_calling_program = gd_repid.
And that's how your CONSTRUCTOR method should look like:
METHOD constructor. " IMPORTING parameter id_calling_program
CALL FUNCTION 'RS_REFRESH_FROM_SELECTOPTIONS'
EXPORTING
CURR_REPORT = id_calling_report
TABLES
SELECTION_TABLE = me->mt_selopts.
" NOTE: define mt_selopts as instance attribute of table type RSPARAMS_TT
ENDMETHOD.
Finally you have to extract the parameter and select-options from MT_SELOPTS.
Regards
Uwe -
Tochange the string in Std Class Builder "New Method"
HI freinds,
Im using the std program of "RFDOPR10"...(changed into my customised program as ZRFDOPR10).....
Here i want to change the strings of Id_type eq 4 availble under the class builder "New Method".
"id_ruler_string = '2.13.24.29|43|58|73|88|103|118|'" (for 24...i want to give 38.....then 45...)
Pls help me how to change the std method function for my z program...
FYR:
RFDOPR10 is the std program for tcode :"s_alr_87012178", Customer analysis.If u want to c the example report, in this tcode...give OI:1, Summ level:6, OI list:1 and Company CD:2 under Output control tab in selection screen with Company code.Now, u able to see the reports in the screen.There, after Customer number....I've to give some more spaces(length) for Sort field.
Thanks & regards
Sankar.Associated with the text box there will be some kind of event handler. Maybe it's an action event on the text box (when the user clicks return) or maybe you have a separate button that the user clicks.
Either way, in the event handler, get the text from the text box, and then call the sendData method, passing the text as an argument. -
Passing custom DTO to input method...
Hi,
Im attempting to create a workshop web service that accesses an EJB control. The
method's input params require the passing of a custom built data transfer object
(bean) that contains itself other objects. is there any way to do this via a web
service thru workshop?John,
A workshop web service (i.e. a JWS file) is analogous to a JSP/servlet. Any
class (bean) that needs to be passed to an EJB Control method should be
accessible to the contaning JWS.
So the bean and all the objects contained/referenced by the bean should be
available in any one of the following 3 ways:
1. System CLASSPATH
2. In the WEB-INF/lib or WEB-INF/classes directory of the Workshop project
3. As a Java file in the Workshop project directory.
I hope this answers your question. Do let me know if I can help further.
Regards,
Anurag
"John Bonham" <[email protected]> wrote in message
news:3e0f058e$[email protected]..
>
Hi,
Im attempting to create a workshop web service that accesses an EJBcontrol. The
method's input params require the passing of a custom built data transferobject
(bean) that contains itself other objects. is there any way to do this viaa web
service thru workshop? -
Passing an array from one method to another
I am passing an array from my "load" method and passing it to be displayed in my "display" method in an applet .
I made the array a class variable (to be able to pass it to the "display" method).
The applet runs, but nothing seems to be in the array.The screen says applet started, but nothing else. There does not seem to be any CPU activity.
Trying to debug this, I have tried to paint the screen during the array build. I never figured out how to do this. So I made this a non applet class, put it in debug, and the array seems to load okay.
Any help is appreciated.
This is the applet code:
import java.applet.Applet;
import java.awt.*;
import java.io.*;
import java.util.*;
import java.net.*;
public class urla extends java.applet.Applet
int par1;
int i = 1;
int j = 20;
int m = 0;
int k = 0;
String arr[] = new String[1000];
String inputLine;
public void load() throws Exception
try
URL mysite = new URL("http://www.xxxxxxxxxxxxxx.html");
URLConnection ms = mysite.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
ms.getInputStream()));
while ((inputLine = in.readLine()) != null)
arr[m] = inputLine;
m++;
in.close();
catch (MalformedURLException e)
k++;
public void display(Graphics screen)
screen.drawString("THE FOLLOWING HAVE ADDED THEIR BIOS:",5 ,5);
for (int i = 0; i < 20; i++);
j = j + 20;
screen.drawString("output - "
+ arr, 5, j);
repaint() ;
}String arr[] = new String[1000];is this typing mistake????? because if u did it in
program as well i don think it will work.. the tag is
innnside array lenght... hope iam saying this right!!no, he had the bold form tags (b and /b inside square brackets) in his previous non-code tagged post. He carried it over to this post and they caused an error. I highly doubt that they were in his actual program. Just delete them.
Message was edited by:
petes1234 -
Passing argstrings[1] to another method
Hello I want to pass argstrings[1] to another method. Other stuff is being passed there to. Before I passed argstrings[1] the other stuff worked, now it does not.
Please tell me why I am getting compilation errors.
Thanks
public static void main(String[] argStrings)
String filePath = null;
if(argStrings.length != 0)
filePath = argStrings[0];
else
System.out.println("Enter a directory please");// Else you have to enter a directory
Scanner scan = new Scanner(System.in);
filePath = scan.nextLine();
String copyDate = argStrings[1];
Date dateToLookFor = new Date(copyDate);
listFiles(filePath);// this no longer works as of the new log(datetolookfor)
log(dateToLookFor);// just wanna pass this to the next method
private static void log(File[] files, Date dateToLookFor)
{Well i only get one compile error, cheers.
So please could you help me what i have to do to this mess in order for it to work:
Or just edit the code as I dont think there is much to do:
Thanks
import java.lang.*;
import java.io.*;
import java.util.*;
* This application identifies files which could potentially be archived
* and copied. A file is to be archived if the last modified date is more
* than 100 days ago. A file is to be copied if it has been modified since
* a given time. Only nominated extensions are to be considered. The java.
* util.Calendar class contains relevant methods for comparing times and dates.
* For instance, a command line of: java CrawlerApp Knuth 2005-12-28 php html
* Will nominate for archiving or copying only php or html files in the Knuth
* directory tree. It will only nominate for copying files modified after
* midnight on the 28th of December, 2005.
* The output from this application is two files (called archive.txt and copy.txt)
* containing the names of files to be archived, and those which may be copied.
* The names will follow the convention specified in the create application.
* These two text files must appear in the root directory (Knuth, in this example).
public class Crawler
public static void main(String[] argStrings)
String name = null;
if(argStrings.length != 0)
name = argStrings[0];
else
System.out.println("Enter a directory please");// Else you have to enter a directory
Scanner scan = new Scanner(System.in);
name = scan.nextLine();
String copyDate = argStrings[1];
listFiles(name, copyDate);
private static void log(String copyDate, File[] files)
PrintStream archivePS = null;
PrintStream copyPS = null;
try
archivePS = new PrintStream("archive.txt");
copyPS = new PrintStream("copy.txt");
// instantiate cutoff Calendar instance to test files with
Calendar cutoff = Calendar.getInstance();
// time now
Date now = new Date();
// set cutoff time with current time
cutoff.setTime(now);
// subtract 100 days from current time
cutoff.add(Calendar.DAY_OF_YEAR, -100);//
Calendar calendar = Calendar.getInstance();
for(int j = 0; j < files.length; j++)
// get last modified time of file
long lastModified = files[j].lastModified();
// convert lastModified to a date
Date lastMod = new Date(lastModified);
// set the time for the Calendar instance with lastMod
calendar.setTime(lastMod);
// test against cutoff Calendar instance variable
if(lastMod.before(cutoff.getTime()))
archivePS.println(files[j]);
if(lastMod.before(cutoff.getTime()))
copyPS.println(files[j]);
// I will do copy later, just want to see if this works
catch(FileNotFoundException fnfe)
System.err.println("Log error: " + fnfe.getMessage());
catch(IOException ioe)
System.err.println("I/O exception: " + ioe.getMessage());
private static void listFiles(String name, String copyDate)
File f = new File(name);// Try to get a list of files in the directory
File[] files = f.listFiles();// Make array of all the files in that directory
log(files, copyDate);
if(f.isDirectory())// If the argStrings[0] is a directory then do the following
File[] children = f.listFiles(HTMLfilter);// Make an array of html files
System.out.println("HTML files in " + name + " directory = " + children.length);
File[] phpFiles = f.listFiles(PHPFilter);// Make an array of php files
System.out.println("PHP files in " + name + " directory = " + phpFiles.length);
private static FileFilter HTMLfilter = new FileFilter()
public boolean accept(File f)// Accept directory Knuth
//if(f.isDirectory()) return true;
String name = f.getName().toLowerCase();
return name.endsWith("html");
//if(file is 100 days old)
private static FileFilter PHPFilter = new FileFilter()
public boolean accept(File f)
//if(f.isDirectory()) return true;
String name = f.getName().toLowerCase();
return name.endsWith("php");
} -
I NEVER USED OOPS CONCEPT.BUT I GOT A TASK ON ALV REPORT USING class CL_GUI_ALV_GRID, call method SET_TABLE_FOR_FIRST_DISPLAY for ALV . I HAD PASSED THE VALUES FROM INTERNAL TABLE AND GOT OUTPUT IN ALV.
The problem is When i save an layout(default setting button ).
iam unable to get the output for all fields.
if u want i will send screenshots to ur mail
THANKS IN ADVANCE.ok fine,
In the output (alv grid) there is an icon for layout settings.
if i want to save layout (as DEFAULT SETTING) i am missing some fields in output
EX:
mat no | batch | proces order | time | date |
when i save layout (as DEFAULT SETTING) i am missing some fields in output
mat no | batch |
the rest of the field were not displayed.
if u are not clear just ask me. i will send some more examples. -
In BADi , How to pass the values between two Method
Hi Experts,
We have two methods in BADis. How to pass the value between two Methods. Can you guys explain me out with one example...
Thanks & Regards,
Sivakumar SHi Sivakumar!
Create a function group.
Define global data (there is a similiar menu point to jump to the top include).
Create one or two function modules, with which you can read and write the global data.
In your BADI methods you can access the global data with help of your function modules. It will stay in memory through the whole transaction.
Regards,
Christian -
Creation of a static class with private methods
I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
Here's my code:
* <p>Title: Order Control </p>
* <p>Description: Order Control Calculator using methods and classes</p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: Info 250, sec 001, T/TH 0930</p>
* @author Peggy Blake
* @version 1.0, 10/29/02
import javax.swing.*;
public class ShippingCalculator
static double firstClass, priorityMail;
//how do I get my weight from another class into this method to use??? not sure I understand how it works.
public static double ShippingCalculator(double weight)
String responseFirstClass;
double quantity, shippingCost;
double totalFirstClass, firstClass, priorityMail, totalShipping;
double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
quantity = 0d;//ititialization of quantity
// weight = 0d;//initialization of weight
// shippingCost = 0d;
//calculation of the number of items ordered..each item weights .75 ounces
quantity = (weight/.75);
if (quantity <= 30d)
//add 1 ounce to quantities that weigh less than 30 ounces
weight = (weight + 1);
else
//add 2 ounces to quantities that weigh more than 30 ounces
weight = (weight + 2);
if (weight > 80d)
//message to orderclerk ..order over 5 lbs, cannot process
JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
//exit system, do not process anything else
System.exit (0);
else
if (weight < 14d)
//send message to customer: ship firstclass or priority, y or n
responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
if (responseFirstClass.equals("y"))
//compute FirstClass shipping cost
totalFirstClass = ((weight - 1) * .23d) + .34d;
firstClass = totalFirstClass;
else
//compute PriorityMail cost for orders less than 14 ounces
priorityMail = (priorityMail1);
else
if (weight <=16d)
//compute totalshipping for orders up to 16 ounces
priorityMail = (priorityMail1);
else
if (weight <=32d)
//compute totalshipping for orders up to 32 ounces
priorityMail = (priorityMail2);
else
if (weight <=48d)
//compute totalshipping for orders up to 48 ounces
priorityMail = (priorityMail3);
else
if (weight <= 64d)
//compute totalshipping for orders up to 64 ounces
priorityMail = (priorityMail4);
else
//compute totalshipping for orders up to 80 ounces
priorityMail = (priorityMail5);
priorityMail = 0d;
firstClass = 0d;
firstClassMail ();
priorityMailCost ();
//I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
shippingCost = priorityMail + firstClass;
return (shippingCost);
}//end method calculate shipping
private static double firstClassMail()//method to get first class ship cost
return (firstClass);
}//end method firstclass shipping
private static double priorityMailCost()//method to get priority mail cost
return (priorityMail);
}//end method priorityMail
}//end class shipping calculatorpublic class A {
public String getXXX () {
public class B {
A a = new A();
public void init () {
a.getXXX();
} -
In which case we need a class with all methods defined as abstract ?
In which case we need : A class with all methods defined as abstract (or should we go for Interface always in this case)
The concept of interface and abstract class overlaps sometime, but we can have the following thumb rule to use them for our specific need:
1) Interface: This should be use for code structuring. They standardize your application by providing a specific contract within and outside. If you think abstract class also provide structure, then reconsider as it limits the structure re-usability when there are many super-classes to inherit from. Java allow multiple inheritance by interface and not by Abstract class.
2) Abstract Class: This should be use for code-reusability. Interface doesn't have any code so can't be used for code-reusability.
Actually we can use both to provide the best.Taking a refernce to J2EE framework, the "Servlet" is an interface. It laids down the contract/structure for any code to be a servlet.
But the "GenericServlet" class is an abstract class which provides implementation of some of the methods defined in the "Servlet" interface and leave some method abstract.
Thus we see that the "Servlet" interface standardise the structure and the "GenericServlet" abstract class gives code re-usability.
Original Question:
In which case we need a class with all methods defined as abstract ?To this question, as all methods are abstarct we don't have option for code-reusability. so why not add standard structure concept to your application. So if there is not any restriction on making the field variable(if any) as final, we should go with the interface concept. -
Server error: Class: UCF Acroform Method error Message: Could not send mess
Hi Gurus,
I'm having a problem with displaying PDF file in the portal. I tried reinstalling Adobe 9. Tick and untick the option Display PDF in browser. But still encountering the error. Is it something to do with IE version? Please Help. Thanks in advance.
Server error: Class: UCF Acroform Method error Message: Could not send messageHi,
Please speify the system information so that I can help you
Regards
Sharanya.R -
How to pass table to in a method as a parameter
Hi
I need to pass one table in one method to another method as a parameter.
ex: it_tab type zvalue(DDIC).
send_mail( it_tab)like this i need to pass. How to do this.
Please help me.
Thanks & Regards
SUNHello,
You'll need a table category that has the same structure of your internal table. Suppose you need to pass an internal table of type SCARR: you'll actually pass a parameter of type SCARR_TAB (look for it into tcode SE11).
Remember that in a OOP scope, you cannot have header line in your internal tables.
Regards,
Andre -
Hi,
In SNC system, the supplier is getting the following error when he is trying to update the planned receipt quantity.
Due to that error the ASN canu2019t be created and sent to ECC system.
Time series error in class /SCF/CL_ICHDM_DATAAXS method /SCF/IF_ICHDMAXS_2_CNTL~SAVE
Please give your inputs as to how to resolve this error.
Regards,
ShivaliHi Shivali,
This is not related to time series data issue.
ASN (ASN number:122593)XML failed may be because of there no Purchase order(Reference order) exists for supplier 0000104466 which will be there in failed XML.(see the DespatchedDeliveryNotification_In XML check XML tag <PurchaseOrderReference> value under tag <Item>)
Login as a supplier 0000104466 and search for purchase order (or replenishment order) and this PO(or RO) won't be there in supplier 0000104466 .
That's why ASN got failed.
Regards,
Nikhil
Maybe you are looking for
-
Auto generation of documents program (mail merge)
hi everyone i wanted to write a program to allow user to create a particular letter just by clicking a button, now this file is first store in xml form, when user initiates the document generation the program will get xml element from the database an
-
I wish to eliminate my stack of CD's by archiving them onto a Hard Disk Drive. I wish to have excellent FLAC files after ripping so that I can enjoy the music quality of the CD in the future, without having the actual CD anymore. Is there a good prog
-
i have had my ipod classic for a year now and when i plug it into my computer it says it is corrupt and that i need to restore it. i did that and it still does nothing. i tried the 5 Rs and that did not help. it also says there is no memory left, eve
-
HT5622 Payment method was declined how to cancel payment
Payment method was declined and an attempt to make a purchase was an accident
-
Line6 Gearbox AudioUnits?
Have any guitarists out there tried the AudioUnit plug-in versions of Line6's GearBox amp modelling software? I've sniffed around some of their product offerings for a while now, but never bought any because as long as I was using amp models I liked