Static methods and how to access
Hi,
This seems like a silly quesion but i am trying to access a static method but it tells me that i cant.
The method i am calling from is not static
Thanks
syntax: class name dot static method name (assuming the method is accessible): StaticMethodClassName.aStaticMethod();
can't reference a class member (variable, object, method, ...) from a static method because a static method is not a class member (it is simply a method whose scope is confined to that of the class in which it is defined).
example:
class Foo
int i;
public static void hasSyntaxErr() // this method is not a member of Foo
i = 0; // not allowed because i is a member of Foo
class Fooo
void testStatic() { Foo.hasSyntaxErr(); }
}
Similar Messages
-
I am using a verizon email address and microsoft office for mac outlook program to manage my emails. Does any one know if the apple outlook version offers the ability to save emails as a pdf so that I can save it to my hard drive and how to access?
This is the Microsoft forum site that parallels what Apple has:
Office for Mac forums
It's not uncommon for MS employees who work with the Mac side of the business to help there. All in all a useful resource for Office:Mac -
Do the Interface contains static components like static methods and attribu
Do the Interface contains static components like static methods and attributes ?
>
You have to supply a bit more detail: is that Lotus
Notes API a Java API?Hmm, It's Java interface to Lotus Notes API
Does it use JNI? Perhaps it is used somewhere underneath, I do not know for sure, but I think so
Possibly the Lotus Notes
implementation keeps a
reference to those arrays, who knows?
Maybe, but I'd be really suprised if it did. I derive this thread from Lotus Notes class and provide my own "worker method", overriding Lotus API abstract one, where I reference arrays. Arrays are specific to my program and since they are private fields in thread's class Lotus Notes layer does not have any way of referencing them, nor any reason for this matter
For starters: if you zero out (set to null) your
references to those arrays
in your threads when the threads finish, there might
surface a useful
indication that you can blame Lotus Notes for this
Well, I've become deeply suspect of whether these Notes' threads do really finish :-) My method finishes for sure, but it is just a part of run() method of Lotus Notes thread. Anyway, you can always safely blame Lotus Notes for almost anything :-) -
Difference between calling static method and not static method?
Hi,
Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?writing the method as static method or not static
method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static. -
Static method and variables doubts
i have a doubt
i have the following method
private static void checkActionType(String action) {
if (action.startsWith(" a")) {
++totalAddedActions;
} else if (action.startsWith(" c")) {
++totalChangedFolders;
} else if (action.startsWith(" p")) {
++totalPersonalizedActions;
} else if (action.startsWith(" r")) {
++totalRemovedActions;
} else if (action.startsWith(" v")) {
++totalViewedActions;
} else if (action.startsWith(" u")) {
++totalUpdateActions;
to use it, i need to declare my int variables static, because im calling this method from another static method that is called by main method.
but this can cause me problems ?
if i have two instances of this class running, my statics int will show the right value?
there is a better approach?Here is my class, i want some advices to know if i am doing right, because everything is a little new for me.
My class, read a log file and based upon a regular expression, it can retrieve a general statistic or a personal statistic.
package br.com.organox.aggregator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import org.apache.oro.text.regex.*;
public class LogFileReader {
private static Pattern regexpPattern;
private static PatternMatcher patternMatcher;
private static PatternCompiler patternCompiler;
private static PatternMatcherInput patternInput;
private static MatchResult matchResult;
private static final String patternString = "^[^\']+User\\s+\'([^\']+)\'[^\']+session\\s+\'([^\']+)\'\\s+(\\S+)";
// Integers used to store number of user, sessions and specific actions
private static int totalUsers;
private static int totalSessions;
private static int totalAddedActions;
private static int totalChangedFolders;
private static int totalPersonalizedActions;
private static int totalRemovedActions;
private static int totalUpdateActions;
private static int totalViewedActions;
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No file name was specified");
printClassUsage();
} else if (args.length == 1) {
printGeneralData(args[0]);
} else if (args.length == 2) {
System.out.println("You must set file name, data value and data type in order to " +
"this class run properly");
printClassUsage();
} else {
printSelectedData(args[0],args[1],args[2]);
public static void printGeneralData(String fileName) {
String data = "";
//Users and the Session Vector are used to avoid count repeated values.
Vector usersVector = new Vector();
Vector sessionVector = new Vector();
patternCompiler = new Perl5Compiler();
patternMatcher = new Perl5Matcher();
try {
regexpPattern = patternCompiler.compile(patternString);
} catch (MalformedPatternException mpe) {
System.out.println("Error Compiling Pattern");
System.out.println(mpe.getMessage());
try {
FileReader fileRead = new FileReader(fileName);
BufferedReader buffRead = new BufferedReader(fileRead);
while ((data = buffRead.readLine())!= null) {
patternInput = new PatternMatcherInput(data);
while(patternMatcher.contains(patternInput,regexpPattern)) {
matchResult = patternMatcher.getMatch();
// Avoid to insert repeated data in user and session Vectors
if (usersVector.lastIndexOf(matchResult.group(1)) == -1) {
usersVector.add(matchResult.group(1));
if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
for (int i=0;i<usersVector.size();i++) {
totalUsers++;
for (int i=0;i<sessionVector.size();i++) {
totalSessions++;
fileRead.close();
buffRead.close();
} catch (IOException ioe) {
System.out.println("An I/O error occurred while getting log file data");
ioe.printStackTrace();
System.out.println("Users logged : " + totalUsers);
System.out.println("Sessions opened : " + totalSessions);
System.out.println("Added contents : " + totalAddedActions);
System.out.println("Changed folders : " + totalChangedFolders);
System.out.println("Personalized contents : " + totalPersonalizedActions);
System.out.println("Removed contents : " + totalRemovedActions);
System.out.println("Viewed Contents : " + totalViewedActions);
System.out.println("Updated contents : " + totalUpdateActions);
public static void printSelectedData(String fileName,String value,String valueType) {
String data = "";
String user = "";
//Flag used to print the right result on screen
String printFlag = "";
Vector sessionVector = new Vector();
Vector userVector = new Vector();
Vector actionVector = new Vector();
patternCompiler = new Perl5Compiler();
patternMatcher = new Perl5Matcher();
try {
regexpPattern = patternCompiler.compile(patternString);
} catch (MalformedPatternException mpe) {
System.out.println("Error Compiling Pattern");
System.out.println(mpe.getMessage());
try {
FileReader fileRead = new FileReader(fileName);
BufferedReader buffRead = new BufferedReader(fileRead);
while ((data = buffRead.readLine())!= null) {
patternInput = new PatternMatcherInput(data);
while(patternMatcher.contains(patternInput,regexpPattern)) {
matchResult = patternMatcher.getMatch();
if (valueType.equalsIgnoreCase("-user")) {
printFlag = "userPrint";
if ((matchResult.group(1).equalsIgnoreCase(value))) {
userVector.add(matchResult.group(1));
// avoid insert a repeated value inside session vector.
if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
if (userVector.size() == 0) {
printFlag = "userPrintError";
} else if (valueType.equalsIgnoreCase("-session")) {
printFlag = "sessionPrint";
if ((matchResult.group(2).equalsIgnoreCase(value))) {
user = matchResult.group(1);
sessionVector.add(matchResult.group(2));
increaseActionType(matchResult.group(3));
if (sessionVector.size() == 0) {
printFlag = "sessionPrintError";
} else if (valueType.equalsIgnoreCase("-action")) {
printFlag = "actionPrint";
if ((matchResult.group(3).equalsIgnoreCase(value))) {
if (userVector.lastIndexOf(matchResult.group(1)) == -1) {
userVector.add(matchResult.group(1));
actionVector.add(matchResult.group(3));
if (actionVector.size() == 0) {
printFlag = "actionPrintError";
fileRead.close();
buffRead.close();
} catch (IOException ioe) {
System.out.println("An I/O error occurred while getting log file data");
ioe.printStackTrace();
if (printFlag.equals("userPrint")) {
for (int i=0;i<sessionVector.size();i++) {
totalSessions++;
System.out.println("Sessions opened by user " + value + " : " + totalSessions);
System.out.println("Added contents by user " + value + " : " + totalAddedActions);
System.out.println("Changed folders by user " + value + " : " + totalChangedFolders);
System.out.println("Personalized contents by user " + value + " : " + totalPersonalizedActions);
System.out.println("Removed contents by user " + value + " : " + totalRemovedActions);
System.out.println("Viewed contents by user " + value + " : " + totalViewedActions);
System.out.println("Updated contents by user " + value + " : " + totalUpdateActions);
} else if (printFlag.equals("userPrintError")) {
System.out.println("This user " + value + " was not found on log file");
} else if (printFlag.equals("sessionPrint")){
System.out.println("Session " + value + " was opened by user " + user);
System.out.println("Added contents by session " + value + " : " + totalAddedActions);
System.out.println("Changed folders by session " + value + " : " + totalChangedFolders);
System.out.println("Personalized contents by session " + value + " : " + totalPersonalizedActions);
System.out.println("Removed contents by session " + value + " : " + totalRemovedActions);
System.out.println("Viewed Contents by session " + value + " : " + totalViewedActions);
System.out.println("Updated contents by session " + value + " : " + totalUpdateActions);
} else if (printFlag.equals("sessionPrintError")){
System.out.println("This session " + value + " was not found on log file");
} else if (printFlag.equals("actionPrint")){
System.out.println("Action " + value + " was performed " + actionVector.size() +
" times for " + userVector.size() + " different user(s)");
} else if (printFlag.equals("actionPrintError")){
System.out.println("This action " + value + " was not found on log file");
} else {
System.out.println("Wrong search type!");
System.out.println("Accepted types are: ");
System.out.println("-user -> Search for a specified user");
System.out.println("-session -> Search for a specified session");
System.out.println("-action -> Search for a specified action");
private static void increaseActionType(String action) {
if (action.startsWith("a")) {
++totalAddedActions;
} else if (action.startsWith("c")) {
++totalChangedFolders;
} else if (action.startsWith("p")) {
++totalPersonalizedActions;
} else if (action.startsWith("r")) {
++totalRemovedActions;
} else if (action.startsWith("v")) {
++totalViewedActions;
} else if (action.startsWith("u")) {
++totalUpdateActions;
} -
I have file which is reading from file and deleting it.
delete is done by static method.
now i need to do like this if file is empty it should throw exception and delte the file.
so i added else like this
else{
throw new empty("Empty");
but it is only thorowing exception not deleting file.as that static code is unreachable after throwing exception.
any ideaHi zodok now this is original file just go through else statement in bold
containing boolean a=deleteFile(fileName);
package com.dhl.auditdatamgr.utils;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import com.dhl.auditdatamgr.business.DetailedFacilityAuditData;
import com.dhl.auditdatamgr.exceptions.FileFormatException;
import com.dhl.auditdatamgr.exceptions.SystemException;
import com.dhl.auditdatamgr.exceptions.EmptyFileException;
import com.dhl.auditdatamgr.utils.db.DataUtil;
* @author mahiseth
public class AuditFileParser
* Constructor
protected AuditFileParser()
super();
public static List parseFile(String fileName, String regex)
throws IllegalArgumentException, FileNotFoundException, FileFormatException,SystemException, EmptyFileException
DataUtil.enforceNotNullOrEmpty(fileName);
DataUtil.enforceNotNullOrEmpty(regex);
List rowList = new ArrayList();
BufferedReader br = null;
try
br = new BufferedReader(
new FileReader(new File(fileName)));
String line = null;
DetailedFacilityAuditData detailedAuditData = null;
Integer huExpected = null;
Integer huMissing = null;
Integer huExtra = null;
Integer shipmentExpected = null;
Integer shipmentMissing = null;
Integer shipmentExtra = null;
Integer pieceIdsExpected = null;
Integer pieceIdsMissing = null;
Integer pieceIdsExtra = null;
Pattern p = Pattern.compile(regex);
//while((line = br.readLine()) != null)
if ((line = br.readLine()) != null){
//System.out.println("Line: " + line);
//Pattern p = Pattern.compile("[\\p{Punct}&&[|]]");
String [] lineItems = p.split(line.trim());
if (lineItems.length != 18){
System.out.println("line = >>" + line + "<<");
System.out.println("lineItems.length = " + lineItems.length);
System.out.println("lineItems = " + java.util.Arrays.asList(lineItems));
detailedAuditData = new DetailedFacilityAuditData();
DataUtil.enforceNotNullOrEmpty(lineItems[0]);
DataUtil.enforceNotNullOrEmpty(lineItems[5]);
DataUtil.enforceNotNullOrEmpty(lineItems[6]);
DataUtil.enforceNotNullOrEmpty(lineItems[3]);
detailedAuditData.setHuid(lineItems[0]);
detailedAuditData.setAuditAtServiceArea(lineItems[5]);
detailedAuditData.setAuditAtFacility(lineItems[6]);
detailedAuditData.setAuditTime(DataUtil.convertToTimestamp(lineItems[3]));
detailedAuditData.setHuType(lineItems[4]);
detailedAuditData.setBuiltAtServiceArea(lineItems[1]);
detailedAuditData.setBuiltAtFacility(lineItems[2]);
if(lineItems[9] != null && !lineItems[9].equals(""))
huExpected = new Integer(Integer.parseInt(lineItems[9]));
detailedAuditData.setHuExpected(huExpected);
if(lineItems[12] != null && !lineItems[12].equals(""))
huMissing = new Integer(Integer.parseInt(lineItems[12]));
detailedAuditData.setHuMissing(huMissing);
if(lineItems[13] != null && !lineItems[13].equals(""))
huExtra = new Integer(Integer.parseInt(lineItems[13]));
detailedAuditData.setHuExtra(huExtra);
if(lineItems[7] != null && !lineItems[7].equals(""))
System.out.println("Shipment expected is: " + lineItems[7]);
shipmentExpected = new Integer(Integer.parseInt(lineItems[7]));
detailedAuditData.setShipmentExpected(shipmentExpected);
if(lineItems[10] != null && !lineItems[10].equals(""))
shipmentMissing = new Integer(Integer.parseInt(lineItems[10]));
detailedAuditData.setShipmentMissing(shipmentMissing);
if(lineItems[11] != null && !lineItems[11].equals(""))
shipmentExtra = new Integer(Integer.parseInt(lineItems[11]));
detailedAuditData.setShipmentExtra(shipmentExtra);
if(lineItems[8] != null && !lineItems[8].equals(""))
pieceIdsExpected = new Integer(Integer.parseInt(lineItems[8]));
detailedAuditData.setPieceIdsExpected(pieceIdsExpected);
if(lineItems[14] != null && !lineItems[14].equals(""))
pieceIdsMissing = new Integer(Integer.parseInt(lineItems[14]));
detailedAuditData.setPieceIdsMissing(pieceIdsMissing);
if(lineItems[15] != null && !lineItems[15].equals(""))
pieceIdsExtra = new Integer(Integer.parseInt(lineItems[15]));
detailedAuditData.setPieceIdsExtra(pieceIdsExtra);
detailedAuditData.setAuditor(lineItems[16]);
detailedAuditData.setAuditDate(DataUtil.convertToDate(lineItems[17]));
rowList.add(detailedAuditData);
} else{
System.out.println("file");
boolean a=deleteFile(fileName);
System.out.println(a);
throw new EmptyFileException("File is Empty");
catch (IOException e)
throw new SystemException("An error occurred while trying to read the audit data file. " ,e);
//e.printStackTrace();
} catch (ParseException e)
throw new FileFormatException("An error occurred while parsing the audit data file. " ,e);
//e.printStackTrace();
catch (ArrayIndexOutOfBoundsException ae)
throw new FileFormatException("A required field is missing. " ,ae);
finally
try
br.close();
} catch (IOException e1)
e1.printStackTrace();
return rowList;
* @param fileName - File name or directory to be deleted
* @return true if and only if the file is successfully deleted, false otherwise
* @throws IllegalArgumentException
public static boolean deleteFile(String fileName)
throws IllegalArgumentException
DataUtil.enforceNotNullOrEmpty(fileName);
File f = new File(fileName);
boolean deleteStatus = false;
deleteStatus = f.delete();
return deleteStatus;
} -
Static method and threads?
I have a question regarding "static". for example, I have the following code
class Test{
public int i=0;
public static calculateInt(){
....some operations on i;
if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
what if I change "public i" to :private i", the same effects?You can't operate on i in a static method, since i is an instance variable.
If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
Java's Thread Tutorial
JavaWorld: Introduction to Java threads
IBM: Introduction to Java threads
Google: java+threads+tutorial
Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html -
Take this:
class test
static int i=j;
static int j=10;
this will give illegal forward reference ....
but this will compile successfully ..
class test
static int i=test1();
static test1()
return 20;
plz assume we have main method in both cases ..
java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
Plz help.
Thanks
Abhishek RoshanWhy second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
Because the implementors of Java intentionally chose to do it that way.
There are TWO stages to the process: preparation (which occurs first) and initialization.
See the Java Language Spec section 12.4.1 'When Initialization Occurs
The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
Then if you check that referenced section 8.3.2.3 you will find this
http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
8.3.2.3. Restrictions on the use of Fields during Initialization
The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
The usage is not on the left hand side of an assignment.
The usage is via a simple name.
C is the innermost class or interface enclosing the usage.
When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'. -
How to return 2 value to a method and how can i get the return value?
hi guys, this is my problem.
private void one(){
two();
private Vector, Vector two(){
return(row, column);
the problem is that I don't know how to call the two() method and return from two() to one().
please help me, i'm very new to programming........
limlthe problem is that I don't know how to call the two()
method and return from two() to one()You can doprivate Vector[] two () {
return new Vector[] {
row,
column
} // as suggested
private void one () {
Vector[] rowAndColumn = two ();
Vector row = rowAndColumn[0];
Vector column = rowAndColumn[1];
}You should consider replacing your Vector with an ArrayList, btw.
Kind regards,
Levi -
How to link 2 objects and how to access entities objects
Hi,
I have 2 tables "Person" and "Adress". Person has a foreign key to Adress. The tables have a primary key (person_id and adress_id) associated with a sequence table. I use entites objects from tables and i defined a creation form for "Person" and a creation form for "Adress".
While the commit, i would like to link person with adress via the foreign key. So i don't know how to obtain "adress_id" from the entity object for setting the foreign key in the object "person".
More, how can i access to the entites objects for accessing information via getter methods.
Thank for your help.Hi,
documented in http://download-uk.oracle.com/docs/html/B25947_01/toc.htm it is explained in http://download-uk.oracle.com/docs/html/B25947_01/bcentities008.htm#sthref464
Exactly the same question got answered yesterday: Re: How I can acess to master entity object from detail entity object
Frank -
How to include limit switches into my control loop and how to access them through Labview
I'm developing a six degrees of freedom machine with servo motors,UMI flex6 and Labview-5.1.I was unable to access the limitswithes.So I would like to know the connections diagram,UMIflex6 board settings and the Vi's to be included in the program.please help me out in solving this problem.
Hi Kolakanuru,
Thanks for using our discussion forums. How you connect your limit switches depends on what type of motion board you are using. For example, if you look at the connection diagram for a PCI-7344, you can see that Forward Limit switches connect to pins 39, 45, 51, and 57. These will then pin out directly to the UMI. For the connection diagram for your particular motion control board, you can go to www.ni.com/manuals and pull up the necessary information. In regards to reading this in LabVIEW, the first thing you will want to check out is Measurement and Automation Explorer. In the interactive windows for your board, you can check the limit switch status there- Press your limit switch on and off and make sure that it changes the LED in MAX. Once that i
s all set, then you can go into LabVIEW and use the "Read Limit Status" VI which you can find in Functions>>All Functions>>NI Measurements>>Motion>>FlexMotion>>Motion I/O palette. Good luck with your application.
Regards
Dan
National Instruments -
Backing up your mac to external drive and how to access individual files
I have managed to back up the information on my computer to a external drive as a whole but need to access different files, projects so that i can then delete them from my computer to save space. how do I access the different files on my external drive???
You CAN access the backed up file from a time machine backup. Just attach the external drive you used for time machine backups to your notebook and then Start Time machine (First under preference - slide the switch to "off" so it does not start an automatic backup right then) Once you open the backup files in Time Machine on your Notebook you can navigate back to older backups to get to that file. (Even if you've deleted it on your notebook after having backed up that file)
NOW - I would recommend having another back up, like the other poster, before you delete the file from your notebook. Redundancy is a good thing. The way time machine works is that over time as your external drive begins to fill it will delete the oldest backup(s) and you could potentially loose that file forever.
I have two other back ups - I have a Super Duper (exact) cloned version of my MBP on a second ext. hard drive. Now, this would not work for you since you want to delete that file from your MBP. Since it is an exact copy if you delete that file from your notebook and then go back to do a back up with Super Duper it would delete that file on the cloned version on your ext. hard drive (too keep them exactly the same). There may be other settings to avoid this, but I generally just use it as a clone. I also have a 3rd mobile hard drive where I set up folders for files I want to keep forever and just drag and drop those onto this drive.
You can cut down on having too many ext. drives if they have a big enough capacity by partitioning them in Disk Utility. (i.e one big drive with a partition for Super Duper and another for standard backups)
Hope that helps a bit.
Thanks.
Mark -
In the past i set up a KNOWCLOUD on a computer which is now defunct. So, i have all my photos and a few itunes stuck in the scam KNOWCLOUD and have now purchased an ipad and i phone. When i try to down load my photos it says save to GOOD, but when i open good it says i need to contact my administrator for password and username. Any suggestions ?
I have the same problem , i've converted my videos to mp4 , by using different programmes and tried to open them in itunes but it didnt .
Some people suggested the following although it didnt help me , it might help you
One suggested to paste the videos that you want in automatically add to itune ( go to your music folder m then click on itunes , then itunes media , and you will find it there )
Others suggested to o to the ontrol panal , then programmes and features m then lick on quick time (. Or itunes) then Change then repair
If it didnt help. And you find another method m please let me know
Thank you -
Is there an equalizer on iTunes 12 and how to access it?
Good morning to all,
I cannot find the equalizer on iTunes 12 for windows 7 whereas in v. 11 it was easily accessible. Does anyone have a hint?
ThanksThanks to all for the answers. The problem is that the menu must be called on via the "alt" (command) key whereas in iTunes 11 the menu was directly accessible. This should be mentioned somewhere for when you switch from 11 to 12 one does not come to the idea to do that...! A simple info in one corner would suffice (press "alt" for menu). And on the iTune help info this is not mentioned at all either....
Again many thanks to all...
Kind regards from France
Ezio -
Static and non-static variables and methods
Hi all,
There's an excellent thread that outlines very clearly the differences between static and non-static:
http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
My skeleton code then looks like this:
public class IMS extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
doPost(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
//get the various parameters...
if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
if(action.equalsIgnoreCase("start"))
try
IMSRequest imsRequest = new IMSRequest();
imsRequest.startIMS(response);
catch(IOException ex)
catch(ClassNotFoundException ex)
else if(action.equalsIgnoreCase("stop"))
try
StopIMS stopIMS = new StopIMS();
stopIMS.stop(response);
catch(IOException ex)
else if(action.equalsIgnoreCase("status"))
try
ViewStatus status = new ViewStatus();
status.view(response);
catch(IOException ex)
else
response.sendRedirect ("/IMS/wrongPassword.html");
public class IMSRequest
//a whole load of other variables
public PrintWriter out;
public int messageNumber;
public int n;
public boolean status = false; //surely this is a static variable?
public String messageData = ""; // and perhaps this too?
public IMSRequest()
public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
try
response.setContentType("text/html");
out = response.getWriter();
for(n = 1 ; ; n++ )
getMessageInstance();
File file = new File("/Users/damian/Desktop/Test/stop_IMS");
if (n == 1 && file.exists())
file.delete();
else if (file.exists())
throw new ServletException();
try
databaseConnect();
catch (ClassNotFoundException e)
//here I start to get compile problems, saying I can't access non-static methods from inside a static method
out.println(FrontPage.displayHeader());
out.println("</BODY>\n</HTML>");
out.close();
Thread.sleep(1000);
catch (Exception e)
}OK, so, specifially, my problem is this:
Do I assume that when I instantiate the object imsRequest thus;
IMSRequest imsRequest = new IMSRequest();
imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
DamianCan I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
If, however, from another class (FrontPage for
example), I call ((new.IMSRequest().writeHTML) or
something like that, then I'm creating a new instance
of IMSRequest (right?)That's what new does, yes.
and therefore I am never going
to see the information I need from my original
IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
On the other hand, IMSRequest is designed to run
continuously (prehaps for hours), so I don't really
want to just print out a continuous stream of stuff to
the browser. How can I though, every so often, call
the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.
Maybe you are looking for
-
Which object's monitor does a synchronized method acquire?
from the Java Tutorial for concurrency programming: " When a thread invokes a synchronized method, it automatically acquires the intrinsic lock _for that method's object_ and releases it when the method returns. The lock release occurs even if the re
-
Is it possible to transfer my tracks to a new ipod?
Because I really don't want the hassle of ripping all those CD's again!
-
Can't import Entourage database despite into Mail despite EVERYTHING?
I want to complete my transition to Apple but have not been able to import my 16GB Entourage 2004 database despite 7 billion (give or take) attempts, and AppleCare support sessions that ended up with the old finger pointing at Microsoft. But rebuildi
-
Indesign CS4, CS5 Mac freezes/How can I get it to run?
I have been using Indesign CS5 Mac version. When I open it, after I make a new document, the color wheel keeps spinning until I force-close the program or restart my machine. I have taken CS5 off of my system and reloaded it with the same conclusion.
-
Importing Photoshop layers in Flash
Hi, I tried to import photoshop layers in flash. But it is coming as bitmap. Is there any way to bring the photoshop layers as shapes with good flash quality. Thanks for your time.