I'd like to define variable which can share values to classes.
so I tried as following.
But It occured error.
How to share a value to classes?
package com.company;
/////// Error occurred ///////
int sharedValue = 100; // <- How to share to classes?
//////////////////////////////
public class Main {
public static void main(String[] args) {
sharedValue += 10;
GlobalTest globalTest = new GlobalTest();
globalTest.printGlobalValue();
}
}
class GlobalTest {
void printGlobalValue() {
System.out.println(sharedValue);
}
}
You can declare it as a static value in your class:
public class Main {
public static int sharedValue = 100;
....
}
and access it from other classes using:
Main.sharedValue
use static in a class instead
public class Blah {
public static int a = 100;
}
can be accessed by Blah.a
You can also add public getter method to access sharedValue as below:
public class Main {
private int sharedValue;
public void setSharedVallue(int sv)
{
sharedValue=sv;
}
public int getSharedvalue()
{
return sharedValue;
}
// Other code.
}
Related
There is an issue int trying to activate a method of a class via Class.forName.
Class:
public class example{
private int number;
static {
System.out.println("example initializing");
}
example(int number) {
this.number = number;
}
public void printFunc() {
System.out.println("Hello World");
}
}
public class Main {
public static void main(String[] args) {
Class<?> oc = Class.forName("example");
oc.printFunc(); //doesnt work
}
}
Issue: static initializiation is printed, however, when trying to activate the printFunc, there is an error: printFunc is undefined for the type Class<capture#5-of ?>
Question: How to activate a function of a Class via Class.forName ?
Use method invocation from reflection:
try {
Class<?> exampleClass = Class.forName("example");
Object exampleObject = exampleClass.newInstance();
Method printFunctionMethod = exampleObject.getClass().getMethod("printFunc");
printFunctionMethod.invoke(exampleObject);
}
catch (Exception e) {}
I'm trying to call getSetting() from SettingsItem.java in SingleChoiceViewHolder.java. Is there a way to call getSetting() while keeping SettingsItem a non-static abstract class? Here's what I tried to add to SingleChoiceViewHolder.java, however Android Studio says that 'SettingsItem' is abstract; cannot be instantiated.:
SettingsItem instance = new SettingsItem();
instance.getSetting();
IntSetting setting = (IntSetting) getSetting();
mTextSettingDescription.setText(setting.getValue());
I also tried I tried converting SettingsItem to an interface and implementing it alongside SingleChoiceViewHolder extends SettingViewHolder but the original problem still remained.
The files are attached below.
SingleChoiceViewHolder.java:
public final class SingleChoiceViewHolder extends SettingViewHolder
{
private SingleChoiceSetting mItem;
private TextView mTextSettingName;
private TextView mTextSettingDescription;
public SingleChoiceViewHolder(View itemView, SettingsAdapter adapter)
{
super(itemView, adapter);
}
#Override
protected void findViews(View root)
{
mTextSettingName = (TextView) root.findViewById(R.id.text_setting_name);
mTextSettingDescription = (TextView) root.findViewById(R.id.text_setting_description);
}
#Override
public void bind(SettingsItem item)
{
mItem = (SingleChoiceSetting) item;
mTextSettingName.setText(item.getNameId());
if (item.getDescriptionId() == R.string.dynamic_descriptionId)
{
SettingsItem instance = new SettingsItem();
instance.getSetting();
IntSetting setting = (IntSetting) getSetting();
mTextSettingDescription.setText(setting.getValue());
}
if (item.getDescriptionId() > 0 && item.getDescriptionId() != R.string.dynamic_descriptionId)
{
mTextSettingDescription.setText(item.getDescriptionId());
}
}
#Override
public void onClick(View clicked)
{
getAdapter().onSingleChoiceClick(mItem);
}
SettingsItem.java:
public abstract class SettingsItem
{
public static final int TYPE_HEADER = 0;
public static final int TYPE_CHECKBOX = 1;
public static final int TYPE_SINGLE_CHOICE = 2;
public static final int TYPE_SLIDER = 3;
public static final int TYPE_SUBMENU = 4;
public static final int TYPE_INPUT_BINDING = 5;
public static final int TYPE_RADIO_BUTTON = 6;
private String mKey;
private String mSection;
private int mFile;
private Setting mSetting;
private int mNameId;
private int mDescriptionId;
public SettingsItem(String key, String section, int file, Setting setting, int nameId, int descriptionId)
{
mKey = key;
mSection = section;
mFile = file;
mSetting = setting;
mNameId = nameId;
mDescriptionId = descriptionId;
}
public String getKey()
{
return mKey;
}
public String getSection()
{
return mSection;
}
public int getFile()
{
return mFile;
}
public Setting getSetting()
{
return mSetting;
}
public void setSetting(Setting setting)
{
mSetting = setting;
}
public int getNameId()
{
return mNameId;
}
public int getDescriptionId()
{
return mDescriptionId;
}
public abstract int getType();
}
Since getSetting() is not a static method, you need to invoke it on an instance of some concrete class that extends the abstract class SettingsItem.
Think about it. If you have two instances of such a class, and the mSetting variable is different for the two instances, which one should be returned from a static-like call to getSetting()?
By definition abstract class means it is not instantiated but you can inherit from it. If you want to create many different objects with the same values but different names you can just extend SettingsItem.
Also, if you want more abstraction for future use you can create an interface with the same methods as the abstract methods in case you need to make customize methods for a different settings item.
Example:
interface SettingsInterface {
void doSomething();
}
class abstract SettingsItem implements SettingsInterface {
public void doSomething() {
System.out.println("Hello");
}
}
class RegularSettings extends SettingsItem {}
class CustomSettings implements SettingsInterface {
public void doSomething() {
System.out.println("Goodbye");
}
}
class TestClass {
public static void testAbstract(SettingsItem extendedAbstract) {
extendedAbstract.doSomething();
}
public static void testInterface(SettingsInterface interface) {
interface.doSomething();
}
public static void main(String[] args) {
SettingsItem abstractExtended = new RegularSettings();
// also could be CustomSettings instead of SettingsInterface
SettingsInterface customClass = new CustomSettings();
testInterface(abstractExtended);
testInterface(customClass);
testAbstract(abstractExtended);
// will throw errors since it doesn't extend SettingsItem
testAbstract(customClass);
}
}
I need to pass a string from class to another class in Java (Bukkit), I have already read some similar questions, but I can't solve the problem.
I have a Main class
public class Main extends JavaPlugin {
#Override
public void onEnable() {
new PlayerListener(this);
this.saveDefaultConfig();
String bannedBlocksString = this.getConfig().getString("bannedBlocks");
}
#Override
public void onDisable() {
}
}
And another class "PlayerListener"
public class PlayerListener implements Listener {
public PlayerListener(Main plugin) {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
// public static final String bannedBlocksString = "DIAMOND_BLOCK; EMERALD_BLOCK";
public static final String[] bannedBlocks = bannedBlocksString.split("; ");
public static boolean isBannedBlock(String[] bannedBlocks, String blockPlaced) {
boolean returnValue = false;
for (String bannedBlock : bannedBlocks) {
if(blockPlaced.equalsIgnoreCase(bannedBlock)){
returnValue = true;
}
}
return returnValue;
}
#EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
String blockPlaced = event.getBlockPlaced().getType().toString();
if(!event.getPlayer().hasPermission("antibuild.block.noplace") && isBannedBlock(bannedBlocks, blockPlaced)) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You can not place this block.");
}
}
}
How can I get the value of bannedBlocksString in Main from the class "PlayerListener"?
Try this, I hope it works:
From Main:
PlayerListener pl = new PlayerListener(this);
this.saveDefaultConfig();
String [] bannedBlocksString = pl.getBannedBlocks();
From PlayerListener you have to declare get method:
public String [] getBannedBlocks(){
return this.bannedBlocks;
}
If you uncomment the bannedBlocksString in the PlayerListener then you can always access it in the Main class using PlayerListener.bannedBlocksString as the variable is static.
If you want to do it the other way arround and assign the value you need to remove the final from the variable and use the code beneath.
PlayerListener.bannedBlocks = bannedBlocksString.split("; ");
I have the constructor Alieni from the subclass Alieni of the class Settore that sets the name ALIENI from the enum Nome to a certain Settore (composed by the integers coordinataX and coordinataY).
The test I'm trying to make is to verify that after running the method Alieni to a Settore(3,10) when I run the method getSettoreNome on the same Settore it should return the name ALIENI but it returns null.
import static org.junit.Assert.*;
public class Settore {
private Nome settoreNome;
private final int coordinataX;
private final int coordinataY;
public Settore (int coordinataX, int coordinataY){
this.coordinataX=coordinataX;
this.coordinataY=coordinataY;
}
public Nome getSettoreNome() {
return settoreNome;
}
public void setSettoreNome(Nome settoreNome) {
this.settoreNome = settoreNome;
}
}
public enum Nome {
SICURO, PERICOLOSO, SCIALUPPA, ALIENI, UMANI
}
public class Alieni extends Settore {
public Alieni(int coordinataX, int coordinataY) {
super(coordinataX, coordinataY);
setSettoreNome(Nome.ALIENI);
}
}
public class AlieniTest {
#Test
public void testAlieni() {
Settore settore = new Settore(3,10);
new Alieni(3,10);
assertEquals(Nome.ALIENI, settore.getSettoreNome());
}
}
You aren't assigning the new instance of Alieni anywhere. Presumably you'd meant to assign it to settore:
public class AlieniTest {
#Test
public void testAlieni() {
Settore settore = new Alieni(3,10);
assertEquals(Nome.ALIENI, settore.getSettoreNome());
}
}
When compiling the following code, i got compile error:
MadScientist.java:27: Error: local variable timeTraveler is accessed from within inner class; needs to be declared final
import java.util.*;
interface TimeTravelCallback {
void leaped(int amount);
}
interface TimeTraveler {
void adjust(int amount);
}
class LinearTimeTraveler implements TimeTraveler {
#Override public void adjust(int amount) {
}
}
public class MadScientist {
public static void main(String[] args) {
MadScientist madScientist = new MadScientist();
TimeTraveler linearTimeTraveler = new LinearTimeTraveler();
madScientist.experiment(linearTimeTraveler);
}
public void experiment(TimeTraveler timeTraveler) {
TimeTravelCallback cb = new TimeTravelCallback() {
#Override public void leaped(int amount) {
timeTraveler.adjust(amount); //error message
}
};
cb.leaped(20);
}
}
If I change
public void experiment(TimeTraveler timeTraveler) {
to
public void experiment(final TimeTraveler timeTraveler) {
then it works.
Is there any other fix without adding the 'final' at the method parameter?
If you want to do any operation on your final variable passed to your method then use any collection api like List.
public void experiment(final List<TimeTraveler> timeTraveler) {
}
Now, you can modify the value inside your list.
If you don't want to add final, you should create a constructor in you inner class TimeTravelCallback and pass the timeTraveler object to this constructor :
TimeTravelCallback cb = new TimeTravelCallback(timeTraveler) {
public TimeTravelCallback(TimeTraveler timeTraveler){
this.timeTraveler = timeTraveler;
}
#Override public void leaped(int amount) {
timeTraveler.adjust(amount); //error message
}
};